I have a TestCase which uses sockets for testing purposes. As you should always close a socket even in the case of some error, I created a context-manager class abstracting a socket.
A test fixture would look like the following, where MyClassToTest is the actual class to test which uses the socket device internally.
with SocketContextManager() as device:
foo = MyClassToTest(device)
# make tests with foo
I would like to avoid having these two line repeated in each of the Test fixture, but placed consistently into setUp. But how should I do this? The following code
def setUp(self):
with SocketContextManager() as device:
self.foo = MyClassToTest(device)
does not work as the device will be closed at the end of setUp. Is there a way to handle the instantiation of the context manager like this, or do I have to repeat it in every test fixture?
According to the documentation for tearDown:
So you can just open the socket in
setUp, and close it intearDown. Even if your test case raises an exception, the socket will still be closed.