def test_successful_handshake(self, monkeypatch, server_payload: Dict):
        """
        This test only covers the bare minimum to make the code
        succeed, and should also be fed actual values
        that the Faktory server produces.
        """
        host_name = "testing host"
        pid = 5
        mocked_socket = MagicMock()

        mocked_get_message = MagicMock(
            return_value=iter(["HI {}".format(json.dumps(server_payload))])
        )
        mocked_validate_handshake = MagicMock()

        conn = Connection(labels=["test suite"])
        monkeypatch.setattr(conn, "socket", mocked_socket)
        monkeypatch.setattr(conn, "get_message", mocked_get_message)
        monkeypatch.setattr(conn, "_validate_handshake", mocked_validate_handshake)
        # Mocked calls based on environment
        monkeypatch.setattr(
            "faktory._proto.socket.gethostname", MagicMock(return_value=host_name)
        )
        monkeypatch.setattr("faktory._proto.os.getpid", MagicMock(return_value=pid))

        conn.validate_connection()

        handshake_response = mocked_validate_handshake.call_args[0][0]
        assert handshake_response["hostname"] == host_name
        assert handshake_response["pid"] == pid
        assert handshake_response["labels"] == conn.labels
    def test_listens_to_worker_id_flag(self, send_worker_id: bool, monkeypatch):
        """This test should ensure that the `send_worker_id` flag is respected."""
        server_payload = {"v": 2}
        host_name = "testing host"
        pid = 5
        worker_id = "unit test worker"
        mocked_socket = MagicMock()

        mocked_get_message = MagicMock(
            return_value=iter(["HI {}".format(json.dumps(server_payload))])
        )
        mocked_validate_handshake = MagicMock()

        conn = Connection(labels=["test suite"], worker_id=worker_id)
        monkeypatch.setattr(conn, "socket", mocked_socket)
        monkeypatch.setattr(conn, "get_message", mocked_get_message)
        monkeypatch.setattr(conn, "_validate_handshake", mocked_validate_handshake)
        # Mocked calls based on environment
        monkeypatch.setattr(
            "faktory._proto.socket.gethostname", MagicMock(return_value=host_name)
        )
        monkeypatch.setattr("faktory._proto.os.getpid", MagicMock(return_value=pid))

        conn.validate_connection(send_worker_id=send_worker_id)

        handshake_response = mocked_validate_handshake.call_args[0][0]
        if send_worker_id:
            assert "wid" in handshake_response
            assert handshake_response["wid"] == worker_id
        else:
            assert "wid" not in handshake_response
    def test_raises_handshake_error_on_bad_initial_connection(self, monkeypatch):
        payload = {"key": "value"}
        mocked_socket = MagicMock()
        mocked_get_message = MagicMock(
            return_value=iter(["A message that doesn't start with HI"])
        )

        conn = Connection()
        monkeypatch.setattr(conn, "socket", mocked_socket)
        monkeypatch.setattr(conn, "get_message", mocked_get_message)
        # Doing nothing symbolizes success
        with pytest.raises(FaktoryHandshakeError):
            conn.validate_connection()
    def test_raises_error_on_bad_handshake_types(self, monkeypatch):
        """
        Based on the existing source code, the requested data will
        have the same structure, but should raise an error on
        incorrectly typed values.
        """
        payload = {"v": "a non integer value"}
        mocked_socket = MagicMock()
        mocked_get_message = MagicMock(
            return_value=iter(["HI {}".format(json.dumps(payload))]))

        conn = Connection()
        monkeypatch.setattr(conn, "socket", mocked_socket)
        monkeypatch.setattr(conn, "get_message", mocked_get_message)

        with pytest.raises(FaktoryHandshakeError):
            conn.validate_connection()
    def test_uses_nonce_if_available(self, nonce: Optional[str], monkeypatch):
        """
        This test should ensure if a nonce is present while initializing
        the connection to the server, its used as they key to sign the
        password.
        """
        server_payload = {"v": 2, "s": nonce}
        host_name = "testing host"
        pid = 5
        worker_id = "unit test worker"
        mocked_socket = MagicMock()
        password = "******"
        faktory_url = "tcp://:{}@localhost:7419".format(password)

        mocked_get_message = MagicMock(
            return_value=iter(["HI {}".format(json.dumps(server_payload))])
        )
        mocked_validate_handshake = MagicMock()

        conn = Connection(faktory_url, labels=["test suite"])
        monkeypatch.setattr(conn, "socket", mocked_socket)
        monkeypatch.setattr(conn, "get_message", mocked_get_message)
        monkeypatch.setattr(conn, "_validate_handshake", mocked_validate_handshake)
        # Mocked calls based on environment
        monkeypatch.setattr(
            "faktory._proto.socket.gethostname", MagicMock(return_value=host_name)
        )
        monkeypatch.setattr("faktory._proto.os.getpid", MagicMock(return_value=pid))

        conn.validate_connection()

        handshake_response = mocked_validate_handshake.call_args[0][0]

        if not nonce:
            assert "pwdhash" not in handshake_response
        else:
            assert "pwdhash" in handshake_response
            hashed_pw = handshake_response["pwdhash"]
            assert hashed_pw != password
            expected_password = hashlib.sha256(
                password.encode() + nonce.encode()
            ).hexdigest()
            assert expected_password == hashed_pw