Alexander Khoroshavin
Alexander Khoroshavin

Reputation: 162

How to test running http.server in Python?

I need to test availability of my server. I've written test:

class TestApp(unittest.TestCase):
    def setUp(self):
        self.child_pid = os.fork()
        if self.child_pid == 0:
            HTTPServer(('localhost', 8000), Handler).serve_forever()

    def test_app(self):
        try:
            urllib.request.urlopen('http://localhost:8000')
        except (URLError, HTTPError) as e:
            self.fail()

But after tests pass there are several python processes that were adopted by init. How to kill subprocess after test is done?

Upvotes: 0

Views: 299

Answers (1)

Alexander Khoroshavin
Alexander Khoroshavin

Reputation: 162

Found solution. Need to use threading module:

class TestApp(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.server = ...
        thread = threading.Thread(target=cls.server.serve_forever)
        thread.start()

    @classmethod
    def tearDownClass(cls):
        cls.server.shutdown()

Upvotes: 2

Related Questions