Search code examples
pythontestingnosenosetests

Sharing objects between setup and teardown functions in nose


I'm using nose and I need to start an HTTP server for a test. I'm starting it in the setup function, and stopping it in the teardown function like this:

from my_service import MyClient, MyServer


def setup():
    global server
    server = MyServer()
    server.start()

def teardown():
    server.stop()


def test_client():
    client = MyClient('localhost', server.port)
    assert client.get_colour() == "blue"

Is there a more elegant way to have the server object available to teardown function and tests other than this global variable? Perhaps a value returned from setup which would be passed as an argument to tests and teardown?


Solution

  • Have you considered unittest? It does exist for this reason, and nose will work with it nicely:

    import unittest
    
    class MyLiveServerTest(unittest.TestCase):
        def setUp(self):
            self.server = MyServer()
            self.server.start()        
    
        def test_client(self):
            client = MyClient('localhost', self.server.port)
            assert client.get_colour() == "blue"
    
        def tearDown(self):
            self.server.stop()