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
  How to write a code with İF function? Aycaaxx 1 503 Nov-03-2020, 05:46 AM
Last Post: deanhystad
  VSCode not able to discover tests rpk2006 5 1,617 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 924 Jun-14-2020, 05:07 PM
Last Post: Larz60+
  StopIteration exception when mock PostgreSQL connection in several tests igor87z 1 880 Jun-10-2020, 06:16 PM
Last Post: ibreeden
  Running tests in a sibling directory to code sodhiar 1 1,206 Nov-07-2019, 11:28 PM
Last Post: MckJohan
  pytest loop through multiple tests? burvil 0 2,409 Sep-26-2019, 11:42 PM
Last Post: burvil
  Python unittest - running multiple tests from CSV file asheru93 0 2,005 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,734 Oct-28-2018, 07:46 PM
Last Post: wavic
  Tests are not running .Dont why shankar 3 4,507 Sep-20-2018, 07:06 AM
Last Post: shankar
  Cant find S3 Read or Write access from Python code tpc 0 1,261 Apr-19-2018, 04:00 AM
Last Post: tpc

Forum Jump:

User Panel Messages

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