1

What should I do to test the login coroutine?

class Client:
    def __init__(self, config=None):
        self.config = config or ('0.0.0.0', 8080)
        self.reader = None
        self.writer = None

        self.connection = asyncio.create_task(self._connect())

    async def _connect(self):
        self.reader, self.writer = await asyncio.open_connection(*self.config)

    async def login(self, username, password):
        await self.connection  # 2

        md5 = hashlib.md5()
        md5.update(username.encode(ENCODING) + password.encode(ENCODING))
        hash_ = md5.hexdigest()

        # `construct` returns message, in bytes, based on parameters.
        login_message = construct(1, username, password, 182, hash_, 157)
        self.writer.write(login_message)  # 1
        await self.writer.drain()

More specifically, I want to test that the login message is always sent in the right format (1), and maybe also the fact that connection should be established first before sending the message (2). Also, I can't run a local copy of the server, if that matters.

Is this possible? Should I even test this?

I'm using pytest, I've tried using a library called pytest-asyncio, but I just do not understand how to test something like this.

  • 1
    Where is `construct` defined? It sounds like you should be testing that function separately. Then you can focus on testing the connection code itself by mocking. See [here](https://medium.com/ideas-at-igenius/testing-asyncio-python-code-with-pytest-a2f3628f82bc) for example. – shadowtalker Mar 27 '20 at 15:17
  • @shadowtalker `construct` is defined in a separate module and is already tested. What if, let's say, I wanna test whether login sends this message at all? The thing is, there are a lot of messages in this protocol and I feel anxious leaving them untested. I guess I'll reread this article and try to figure out how to mock. – Viktor Astakhov Mar 27 '20 at 15:27
  • 1
    Start a fake server before the test that e.g. puts all incoming messages in a queue. In the test, call `client.login()`. Verify the server queue contains all messages you'd expect the client to send. You probably don't even need to mock anything. – hoefling Mar 27 '20 at 16:44

0 Answers0