Django 测试 - 启动多个可以通信的测试服务器?

Rap*_*ael 5 python django selenium django-testing

我想知道是否可以使用 TestCase 或 LiveServerTestCase 运行 django 测试来模拟多个服务器的存在。

例如,我想使用 Firefox 在本地主机端口 8081 上启动“客户端服务器”,并使用 Chrome 在端口 8082 上启动“资源服务器”。客户端服务器应该能够向资源服务器发出请求以检索 json 数据。每个服务器都应该可以配置自己的设置。简而言之,我想做一些类似的事情

MyTestCase(LiveServerTestCase):
    @override_settings(DATABASE={... client db config ...})
    def launch_client(self):
        self.client = webdriver.Firefox() # on port 8081

    @override_settings(DATABASE={... resource db config ...})
    def launch_resource(self):
        self.resource = webdriver.Chrome() # on port 8082   

    def test_get_json(self):
        self.client.get('http://127.0.0:8082/get/data/') # which should return data from the resource server ...
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经提出了以下解决方案,但这些解决方案不起作用:

  1. 最基本的:使用 LiveServerTestCase 同时启动两个网络驱动程序。IE

    class MySeleniumTests(LiveServerTestCase):
    
        @classmethod
        def setUpClass(cls):
            cls.selenium_chrome = webdriver.Chrome()
            cls.selenium_firefox = webdriver.Firefox()
            super(MySeleniumTests, cls).setUpClass()
    
    Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为两个网络驱动程序将在同一端口上运行,并且不允许在每个服务器上进行不同的设置。

  1. 将 django鼻子与多进程选项一起使用(https://github.com/nosedjango/nosedjango#parallel-test-running-via-multiprocess)。但这只是单独运行测试。

  2. 按照此处所述使用 pyvows ( https://realpython.com/blog/python/asynchronous-testing-with-django-and-pyvows/ )。此选项实际上在多个端口上启动多个应用程序,但会产生非常不一致的结果(线程找不到其服务器等)。此外,如果没有黑客攻击,向另一台服务器请求另一台服务器是行不通的。

有什么想法吗?非常感谢。

小智 1

您可以使用多个 LiveServerThread 而不是仅一个 LiveServerThread 来实现自己的 LiveServerTestCase mixin。