使用 Django 测试获取 live_server fixture
Getting live_server fixture with Django test working
我想同时使用 pytest
、pytest-django
和 pytest-selenium
来测试我的 Django 应用程序功能。如果我用 python manage.py runserver
手动启动服务器并手动输入 URL,它工作正常。
pytest-django
中的 live_server
fixture 应该在我可以使用的后台启动服务器进程,但它不起作用。我没有通过测试,而是 "The requested resource was not found on this server."
以下是我文件的相关部分:
pytest.ini
[pytest]
DJANGO_SETTINGS_MODULE = chatsite_api.settings.test
addopts = --liveserver localhost:8080 --cov=. --cov-report=html --driver Firefox
test_pages.py
import pytest
def test_homepage(selenium, live_server):
selenium.get(live_server.url)
assert "Django: the Web framework" in selenium.title
和chatsite_api.settings.test.py
from .dev import * # NOQA
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}}
DEBUG = True
正如我所说,当我自己启动服务器时,测试 运行 很好,但是 live_server 装置似乎没有按预期运行。我已经验证 live_server.url
是根据 pytest.ini 中的 addopts
行设置的,但这是我所得到的。
如果您正在针对默认索引页面(带有 "The install worked successfully! Congratulations!" 问候语的页面)进行测试,它仅在 运行 带有 DEBUG = True
的开发服务器时显示。特别是,它不会出现在测试中。如果你想使用视图,你需要像其他视图一样在 urls
模块中显式配置它:
# urls.py
from django.urls import path
from django.views.debug import default_urlconf
urlpatterns = [
path('', default_urlconf, name='index'),
]
我想同时使用 pytest
、pytest-django
和 pytest-selenium
来测试我的 Django 应用程序功能。如果我用 python manage.py runserver
手动启动服务器并手动输入 URL,它工作正常。
pytest-django
中的 live_server
fixture 应该在我可以使用的后台启动服务器进程,但它不起作用。我没有通过测试,而是 "The requested resource was not found on this server."
以下是我文件的相关部分:
pytest.ini
[pytest]
DJANGO_SETTINGS_MODULE = chatsite_api.settings.test
addopts = --liveserver localhost:8080 --cov=. --cov-report=html --driver Firefox
test_pages.py
import pytest
def test_homepage(selenium, live_server):
selenium.get(live_server.url)
assert "Django: the Web framework" in selenium.title
和chatsite_api.settings.test.py
from .dev import * # NOQA
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}}
DEBUG = True
正如我所说,当我自己启动服务器时,测试 运行 很好,但是 live_server 装置似乎没有按预期运行。我已经验证 live_server.url
是根据 pytest.ini 中的 addopts
行设置的,但这是我所得到的。
如果您正在针对默认索引页面(带有 "The install worked successfully! Congratulations!" 问候语的页面)进行测试,它仅在 运行 带有 DEBUG = True
的开发服务器时显示。特别是,它不会出现在测试中。如果你想使用视图,你需要像其他视图一样在 urls
模块中显式配置它:
# urls.py
from django.urls import path
from django.views.debug import default_urlconf
urlpatterns = [
path('', default_urlconf, name='index'),
]