dsa-ou / algoesup

Algorithmic essays support: examples, templates, guides, library
https://dsa-ou.github.io/algoesup/
BSD 3-Clause "New" or "Revised" License
2 stars 0 forks source link

Support the testing of methods #1

Open mwermelinger opened 8 months ago

mwermelinger commented 8 months ago

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:

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.