Python Forum
How do i write tests for this code?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do i write tests for this code?
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
    message = data.decode()
    address, *command = map(str.strip, message.split(":"))

    response = await executeCmd(address, command)

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


async def main() -> None:
    server = await asyncio.start_server(

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

    async with server:
        await server.serve_forever()

if __name__ == "__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."""
        reader, writer = await asyncio.open_connection(
            ClientSettings.SERVER, ClientSettings.PORT)

        print(f"Send: {command}")

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

        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( as commands:

        # TODO: Validation required to check for IP address in the subnet 137.72.95.*
        for cmd in commands:

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

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
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.

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to write a code with İF function? Aycaaxx 1 524 Nov-03-2020, 05:46 AM
Last Post: deanhystad
  VSCode not able to discover tests rpk2006 5 1,668 Jul-15-2020, 06:03 AM
Last Post: ndc85430
  Hi Guys, please help me to write SAS macro parameter equivalent code in Python Manohar9589 2 941 Jun-14-2020, 05:07 PM
Last Post: Larz60+
  StopIteration exception when mock PostgreSQL connection in several tests igor87z 1 907 Jun-10-2020, 06:16 PM
Last Post: ibreeden
  Running tests in a sibling directory to code sodhiar 1 1,223 Nov-07-2019, 11:28 PM
Last Post: MckJohan
  pytest loop through multiple tests? burvil 0 2,422 Sep-26-2019, 11:42 PM
Last Post: burvil
  Python unittest - running multiple tests from CSV file asheru93 0 2,020 Jan-21-2019, 08:26 AM
Last Post: asheru93
  How to write a code to get this kind of output in IDLE kavindu 5 1,740 Oct-28-2018, 07:46 PM
Last Post: wavic
  Tests are not running .Dont why shankar 3 4,530 Sep-20-2018, 07:06 AM
Last Post: shankar
  Cant find S3 Read or Write access from Python code tpc 0 1,268 Apr-19-2018, 04:00 AM
Last Post: tpc

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020