当我运行多个测试时,Django LiveServerTestCase无法加载页面

Sas*_*nko 5 python django selenium selenium-webdriver

我正在尝试在一个Django LiveServerTestCase中运行多个测试。当我运行任何单个测试(并带有其他评论)时,一切都会按预期进行。但是,当我用两个测试运行测试用例时,第一个工作正常,但第二个加载页面时显示“内部服务器错误”消息。

码:

from django.test import LiveServerTestCase
from selenium.webdriver.firefox.webdriver import WebDriver


class MyLiveServerTestCase(LiveServerTestCase):    
    """
    BaseCleass for my selenium test cases
    """
    @classmethod
    def setUpClass(cls):
        cls.driver = WebDriver()
        cls.url = cls.live_server_url    

        super(MyLiveServerTestCase, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        cls.driver.quit()
        super(MyLiveServerTestCase, cls).tearDownClass()

class AdminEditFormTest(MyLiveServerTestCase):
    """
    Some test case
    """

    def test_valid_data(self):
        """
        test when user enters correct data
        """
        self.driver.get(self.url)
        # ...

    def test_invalid_data(self):
        """ test when user enters INcorrect data """
        self.driver.get(self.url)
        # ...
Run Code Online (Sandbox Code Playgroud)

如果我使用它close()而不是quit()它,则会失败,并显示“错误98:地址已在使用中”,类似于情况,除了仅当我在一个LiveServerTestCase类中具有多个测试或在一个.py文件中具有多个测试用例时才出现错误。

如何在tearDown上使LiveServerTestCase空闲端口(如果这是核心问题)?

有什么解决方法吗?我想要的只是功能性的硒测试,它们在本地和远程服务器上均能运行。

我正在使用Django 1.6.7,Firefox 37.0,Selenium 2.45.0

更新

使用方法代替类方法会导致相同的问题。

def setUp(self):
    self.driver = WebDriver()
    self.url = self.live_server_url    

def tearDown(self):
    self.driver.quit()
Run Code Online (Sandbox Code Playgroud)

Sas*_*nko 3

最后,出现“内部服务器错误”消息的原因是 WebDriver 从数据库中删除了所有数据quit()包括 contenttypes 和其他默认表

当尝试在下一次测试开始时加载夹具时,这会导致错误。

注意此行为实际上是由于测试运行后TransactionTestCase(从中继承)重置数据库的方式造成的:它截断了所有表LiveServerTestCase


到目前为止,我的解决方案是在每次测试运行时加载带有所有数据(也是“默认”Django 数据,例如内容类型)的装置。

class MyLiveServerTestCase(LiveServerTestCase):    
    """
    BaseClass for my Selenium test cases
    """
    fixtures = ['my_fixture_with_all_default_stuff_and_testing_data.json']

    @classmethod
    def setUpClass(cls):
        cls.driver = WebDriver()
        cls.url = cls.live_server_url    
        super(MyLiveServerTestCase, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        cls.driver.quit()
        super(MyLiveServerTestCase, cls).tearDownClass()
Run Code Online (Sandbox Code Playgroud)

感谢@help_asap 指出这个刷新数据库的quit()问题!

  • 非常感谢您澄清为什么我的第一个“LiveServerTestCase”测试工作正常,但我的第二个测试却给出了如此奇怪的错误。*未来的谷歌用户请注意*,如果您需要一个不执行此操作的“LiveServerTestCase”版本,您可以使用“class RealTransactionalLiveServerTestCase(LiveServerTestCase, TestCase): pass”从“TestCase”获取实际的事务功能。 (3认同)