Testing the Python layer with unittest
The Python layer has two things to test: the function that calls the C# program and the handler that serves the answers. The first test is a real call and pays 88 milliseconds; the second does not need the core at all, because the handler takes the price function as an argument and a test can pass a fake one.
The tests
Two test classes. PriceTest runs the real program and compares the answers with the protocol. HandlerTest starts a server on port 0, which the system assigns, in a thread, and posts to it:
#!/usr/bin/env python3
"""Tests of the Python layer with unittest."""
import threading
import unittest
import urllib.request
from http.server import HTTPServer
from service import make_handler, price
class PriceTest(unittest.TestCase):
def test_a_valid_line(self):
self.assertEqual(price("sku=pen qty=2 unit=1.50"), "ok 3.00 0.60 3.60")
def test_an_invalid_quantity(self):
self.assertEqual(price("sku=pen qty=0 unit=1.50"), "err qty must be 1 to 100")
def test_a_malformed_line(self):
self.assertTrue(price("pen 2 1.50").startswith("err"))
class HandlerTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.server = HTTPServer(("127.0.0.1", 0), make_handler(lambda line: f"echo {line}"))
cls.port = cls.server.server_address[1]
cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True)
cls.thread.start()
@classmethod
def tearDownClass(cls):
cls.server.shutdown()
cls.server.server_close()
def post(self, line):
request = urllib.request.Request(
f"http://127.0.0.1:{self.port}/price", data=line.encode(), method="POST"
)
with urllib.request.urlopen(request) as response:
return response.read().decode()
def test_the_body_reaches_the_price_function(self):
self.assertEqual(self.post("sku=pen qty=2 unit=1.50"), "echo sku=pen qty=2 unit=1.50")
def test_an_empty_body(self):
self.assertEqual(self.post(""), "echo ")
if __name__ == "__main__":
unittest.main()
The fake price
make_handler(lambda line: f"echo {line}") is the whole of the fast test: the server, the request, the body and the answer are real, and the pricing is a lambda. A test that covers the transport does not need the core, and a test that covers the core does not need the server, which is the reason the handler takes a function instead of calling price directly.
- Port 0 asks the operating system for a free port, so the tests can run together and on a machine where 8080 is taken.
- The server runs in a daemon thread and is shut down in tearDownClass, so a failed test does not leave a process of the test runner listening.
- The three tests of PriceTest are slow in the sense of a unit suite: each runs the C# program. They are the tests that would catch a change in the core, and the page of the C# driver is their faster counterpart.
The run
python3 -m unittest -v from the folder of the file, or python3 test_service.py -v:
python3 test_service.py -v
echo "status: $?"
test_an_empty_body (__main__.HandlerTest.test_an_empty_body) ... ok
test_the_body_reaches_the_price_function (__main__.HandlerTest.test_the_body_reaches_the_price_function) ... ok
test_a_malformed_line (__main__.PriceTest.test_a_malformed_line) ... ok
test_a_valid_line (__main__.PriceTest.test_a_valid_line) ... ok
test_an_invalid_quantity (__main__.PriceTest.test_an_invalid_quantity) ... ok
----------------------------------------------------------------------
Ran 5 tests in 0.333s
OK
status: 0
The five tests ran in 0.333 seconds, and the status is zero. The number is dominated by the three real calls to the C# program, which is the honest cost of a test that crosses the boundary. The tests did not need a line for the two environment settings of the service: the path still defaults to the checkout, and the handler tests never bind a public address because the server they start is on 127.0.0.1 port 0.
The next page tests the other side of the boundary: the C# core, with a driver of its own.
Exercises
- Add a test for an answer that does not start with ok or err.
- Test the handler with a price function that raises an exception and decide what the server should answer.
- Make the server watch a request that times out and check that the test fails.
- Run the tests with -k Handler and compare the time with the full run.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
How many tests does the page run?
Answer
Five: three of the price function and two of the handler
The measured run says Ran 5 tests.
-
Why does the handler take the price function as an argument?
Answer
A test can pass a fake one and skip the C# process
The fast tests use a lambda.
-
What does this program print?
Console.WriteLine("ok");Answer
ok
The fake price of the handler test echoes, and the real one answers ok for a valid line.
-
What does port 0 mean in a test server?
Answer
The system assigns a free port
The test reads the port from server_address.
-
What does this program print?
var tests = new[] { "a", "b", "c", "d", "e" }; Console.WriteLine(tests.Length);Answer
5
The measured run of the page has five tests.
-
Why is the suite 0.796 seconds long?
Answer
Three tests run the C# program, and each pays its start
The page names the boundary as the cost.
-
What does this program print?
var seconds = 0.796; Console.WriteLine(seconds < 1);Answer
True
A comparison of the suite time with a second is true.
-
How is the test server stopped?
Answer
shutdown and server_close in tearDownClass
The page says a failed test must not leave a listener.
-
What would catch a change in the core?
Answer
The PriceTest cases, which call the real program
The page calls them the counterpart of the C# driver.
-
What does unittest need to run the file?
Answer
Python only: unittest is in the standard library
The command is python3 test_service.py -v.
The C# code on this page was built with the .NET SDK 10.0.303 and the Python code was run with Python 3.14.10, on Alpine Linux 3.24.3 (x86_64, four processors) in a Docker container.
Article author: Arthur Isaev