'teardown of a singleton class in pytest
I have a singleton class I'm using in the application (Singleton is implemented in metaclass)
class Singleton(type):
def __init__(self, *args, **kwargs):
self.__instance = None
super(Singleton, self).__init__(*args, **kwargs)
def __call__(self, *args, **kwargs):
if self.__instance is None:
self.__instance = super(Singleton, self).__call__(*args, **kwargs)
return self.__instance
else:
return self.__instance
class ApplicationContext(object):
__metaclass__ = Singleton
def __init__(self, db):
pass
Now I want this object to be in a py.test context - but I want it out of the way in some tests. I tried to create a teardown function but it didn't seem to work...
@pytest.fixture
def context(db, request):
_context = ApplicationContext(db)
def teardown():
print 'teardown'
del _context #this is not working. What should be done here?
request.addfinalizer(teardown)
return _context
Solution 1:[1]
It is a bit hard to say what you mean with:
Now I want this object to be in a py.test context - but I want it out of the way in some tests.
Since we're talking about a singleton, I assume you want the fixture to be available, but not effective in all tests. In that case, Pytest fixtures can have a scope, quoting the relevent part form the docs:
Fixtures requiring network access depend on connectivity and are usually time-expensive to create. Extending the previous example, we can add a scope="module" parameter to the @pytest.fixture invocation to cause a smtp_connection fixture function, responsible to create a connection to a preexisting SMTP server, to only be invoked once per test module (the default is to invoke once per test function). Multiple test functions in a test module will thus each receive the same smtp_connection fixture instance, thus saving time. Possible values for scope are: function, class, module, package or session.
So in your case I'd assume the (default) scope of function should do what you want: the fixture is available in the module (scope), but you have to explicitly use it in each function (out of the way).
Maybe I got your question wrong, but an alternative approach could be to mock the Singleton in your ApplicationContext in your fixture.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bastian Venthur |
