Python Forum
How do i write tests for this code? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How do i write tests for this code? (/thread-17887.html)



How do i write tests for this code? - hshivaraj - Apr-27-2019

Hi all.

I wrote a sample code recently. And I want to write some tests and I cant get my head around if I got my structure right. I have a few question. I know there many of you here much experienced than I am. And I need your opinion

1. I need some help understand if you would have approached this differently or write this differently?
2. How do you write tests, or is it even worth writing test at all for this? As you can for each incoming connection executeCmd is called. Which is where the business logic. Everything around is just handling connections etc.
3. Finally do you think this a clean code. If not how can i improve it?

async def listen(reader: StreamReader, writer: StreamWriter) -> None:
    """."""
    data = await reader.read(ServerSettings.MAX_READ_BYTES)
    message = data.decode()
    address, *command = map(str.strip, message.split(":"))

    response = await executeCmd(address, command)

    print(f"Response to {address}: {response}")
    writer.write(str(response).encode())
    await writer.drain()

    writer.close()


async def main() -> None:
    """."""
    server = await asyncio.start_server(
        listen,
        ServerSettings.HOSTNAME,
        ServerSettings.PORT)

    address = server.sockets[0].getsockname()
    print(f"Server listening on {address!r}")

    async with server:
        await server.serve_forever()


if __name__ == "__main__":
    asyncio.run(main())
I really appreciate your help.

Just to give a bit more context. The client makes a request to the server with value. This is a value the server would wait before responding to the client. Hence the asyncio. The client code looks like

import asyncio

from config import ClientSettings


async def invoke_command(command: str) -> int:
    """Invokes a server method executeCmd with the command returns the response code."""
    try:
        reader, writer = await asyncio.open_connection(
            ClientSettings.SERVER, ClientSettings.PORT)

        print(f"Send: {command}")
        writer.write(command.encode())

        data = await reader.read(ClientSettings.MAX_READ_BYTES)
        response = int(data.decode("utf-8"))
        print(f"Received: {response}")

        writer.close()
        return response

    except ConnectionError as ex:
        print(f"Connection to the server failed: {ex}")

        # Returning 0 to keep it neutral. Returning negative value will impact the total sum
        return 0


async def main() -> None:
    """Main method which creates the asynchronous tasks and collects all responses."""
    tasks = list()

    with open(ClientSettings.data) as commands:

        # TODO: Validation required to check for IP address in the subnet 137.72.95.*
        for cmd in commands:
            tasks.append(invoke_command(cmd))

    responses = await asyncio.gather(*tasks)
    print()
    print(f"Total response - {sum(responses)}")


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
The executeCmd in the server does exactly the wait bit. Which use ayncio.sleep to wait for the number seconds client requested for before responding. I want to write some test for this code. And im finding it hard or not able to think where to start.