简体   繁体   English

如何在 Python 中测试运行 http.server?

[英]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.但是在测试通过后,init 采用了几个 python 进程。 How to kill subprocess after test is done?测试完成后如何杀死子进程?

Found solution.找到解决方案。 Need to use threading module:需要使用threading模块:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM