Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python 'with' statement and its use in a class

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?

like image 430
Alex Avatar asked Jun 04 '26 15:06

Alex


1 Answers

According to the documentation for tearDown:

This is called even if the test method raised an exception

So you can just open the socket in setUp, and close it in tearDown. Even if your test case raises an exception, the socket will still be closed.

like image 94
BrenBarn Avatar answered Jun 06 '26 03:06

BrenBarn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!