Search code examples
pythonpytestc-api

Running several tests with single initialization/destruction of objects to test


TL;DR: is it possible with pytest to create an instance of an object and then run a battery of tests on the same instance ?

I have a custom C API, that uses posix threads and does operations on serial ports. My API is an implementation of a custom/proprietary protocol with a master/slave messaging. With simple test programs in C (or in Python), it works correctly.

But, with pytest, when testing sending and reception of messages, pytest repeatdly open/close the COM port and create/delete the background thread, as each unit test is written in the following manner:

def test_send_message_XXX(serial1, serial2):
    master = my_api.Master(serial1)
    slave = my_api.Slave(serial2)
    message = my_api.SomeCustomMessage()
    master.send_message(message)
    ## tempo to be sure the message was sent
    time.sleep(0.5)
    rec = slave.receive()
    slave.close()
    ## master is closed when the object is destroyed
    assert rec == message.data

The problem is that, most of the time, when I run the tests, I have either a pytest crash (ending with a segfault), or some random cases where the COM port cannot be opened, or is opened but read throws a bad file descriptor (running ls /dev shows the serial devices, and some other "lower level" tests are running correctly).

When I use this API in a "production" (simulated) context, these errors never shows up.

Is there a way to initialize master and slave only once, and then run all the tests on the same instances ?


Solution

  • You can use Fixtures or set-up/tear-down fixtures