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?
#1
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  write code that resides in parent directory franklin97355 0 60 Today, 12:03 AM
Last Post: franklin97355
  needing some help to write some code for a game calculator rymdaksel 1 358 Jan-02-2024, 09:56 AM
Last Post: deanhystad
  Ran 0 tests in 0.000s - unittest Peaches 8 4,930 Dec-31-2021, 08:58 AM
Last Post: Peaches
  How to write a code with İF function? Aycaaxx 1 1,780 Nov-03-2020, 05:46 AM
Last Post: deanhystad
  VSCode not able to discover tests rpk2006 5 10,714 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 2,541 Jun-14-2020, 05:07 PM
Last Post: Larz60+
  StopIteration exception when mock PostgreSQL connection in several tests igor87z 1 2,879 Jun-10-2020, 06:16 PM
Last Post: ibreeden
  Running tests in a sibling directory to code sodhiar 1 2,666 Nov-07-2019, 11:28 PM
Last Post: MckJohan
  pytest loop through multiple tests? burvil 0 4,283 Sep-26-2019, 11:42 PM
Last Post: burvil
  Python unittest - running multiple tests from CSV file asheru93 0 4,153 Jan-21-2019, 08:26 AM
Last Post: asheru93

Forum Jump:

User Panel Messages

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