Open
Description
Essays can also be about data structures, e.g. comparing two implementations of the same ADT. Normally, each implementation is a class, so the library should make it easier to test methods, besides functions. Here's one possible suggestion how to go about it:
- The class must allow parametrised initialisation.
- The class author must write for each method (at least for the modifiers), one test function that takes an already initialised object of that class.
- The class author must provide a list of arguments to initialise the class with.
- Then call a function that runs all tests on all possible instances.
class ArrayStack:
def __init__(items):
"""Initialise a stack with the given items."""
...
def pop(...):
class LinkedListStack:
....
Stack = LinkedListStack | ArrayStack
def test_pop(stack: Stack):
"""Check the `pop` method on the (possibly empty) `stack`."""
...
init_stack = [ # sequences of items to push on the stack before testing it
[],
"abc",
(True, False),
...
]
for class in (ArrayStack, LinkedListStack):
test_methods(class, init_stack)
The last line does the following:
for items in init_stack:
test_pop(ArrayStack(items))
test_push(ArrayStack(items))
...
and then the same for the other stack implementation. More generally, it creates one instance of the class (first argument) for each initialisation argument (second argument), for each method m
for which a function named test_m
exists.
The question remains on how to detect and report failed tests. pytest
introspects the assert
statement to report why it fails.