仅当 运行 pytest 时,在 settings.py 中更改 Django 设置 ALLOWED_HOSTS

Change Django setting ALLOWED_HOSTS in settings.py only when running pytest

我正在尝试 运行 我登录到我的 django 应用程序的测试:

class FirefoxTestCases(StaticLiveServerTestCase):
    def setUp(self):
        data_setup.basic_apps_setup(self)
        self.browser = webdriver.Firefox()

    def tearDown(self):
        self.browser.quit()

    def test_log_in_with_no_apps_displays_firefox(self):
        # Opening the link we want to test
        self.browser.get(self.live_server_url)
        assert "log in" in self.browser.page_source
        time.sleep(2)
        self.browser.find_element_by_id("id_username").send_keys("userone")
        self.browser.find_element_by_id("id_password").send_keys("test")
        self.browser.find_element_by_id("log_in").click()
        time.sleep(2)
        # Check the returned result
        assert "Something appears to be missing" in self.browser.page_source

这样做 - 它实际上不允许登录,因为在我的设置中我有特定的 ALLOWED_HOSTS 设置。

有没有办法在 运行 进行此测试时访问 ALLOWED_HOSTS 设置,以便在测试时允许登录?

问题是在 settings.py 中设置了 SESSION_COOKIE_DOMAIN

例如:

SESSION_COOKIE_DOMAIN = ".company.com"

Django LiveServerTestCase 仅执行 localhost(据我所知是不可更改的)。因此,登录用户的 cookie 未被 localhost

的站点识别

为了解决此问题 - 对于需要交互性(例如登录)的测试,您可以 override that setting 像这样:

from django.test.utils import override_settings
...

...
@override_settings(SESSION_COOKIE_DOMAIN="")
def test_log_in_with_no_apps_displays_firefox(self):
    # Opening the link we want to test
    self.browser.get(self.live_server_url)
    assert "log in" in self.browser.page_source
    time.sleep(2)
    self.browser.find_element_by_id("id_username").send_keys("userone")
    self.browser.find_element_by_id("id_password").send_keys("test")
    self.browser.find_element_by_id("log_in").click()
    time.sleep(2)
    # Check the returned result
    assert "Something appears to be missing" in self.browser.page_source

此测试将覆盖该设置,用户将能够顺利登录。

由于 cookie 问题,网站通常具有的任何其他功能现在都已解决。