by masklinn · 4y ago · 0 comments
@pytest.fixture
def libfact():
yield CDLL("./fact.so")
FWIW that's pretty confusing as it gives the impression the library is reloaded for every test, but iirc dlopen() will just return a handle to the existing one. I don't think ctypes has a good way to unload dlls so it should probably be `fixture(scope='session')`.That gets more relevant when on-the-fly compilation is added to the mix, spawning a compiler for every test is a complete waste of time.
import _ctypes
import shutil
import tempfile
@pytest.fixture
def libfact():
tmp = tempfile.NamedTemporaryFile(delete=True)
shutil.copy2("./fact.so", tmp.name)
lib = CDLL(tmp.name)
yield lib
_ctypes.dlclose(lib.handle)
EDIT: fixed error mentioned in reply. import shutil
import tempfile
@pytest.fixture
def libfact():
tmp = tempfile.TemporaryFile()
tmp_name = f"/dev/fd/{tmp.name}"
shutil.copy2("./fact.so", tmp_name)
lib = CDLL(tmp_name)
yield lib
It's better than relying on your application to clean up the file for you. With application-level cleanup hooks, you're still vulnerable to a resource leak if the process gets a SIGKILL or crashes or otherwise ends before your hooks run.For the rare occurrence of sigkill before cleanup, I think your /tmp has ample of space to keep a few more kb until the next reboot. Servers running tests probably restart more often than desktops nowadays, when wrapped in containers.