在您的Django 项目中,安装以下Python 包:
修改项目的结构以满足行为结构要求。在您的 Django 应用程序目录中,为测试场景文件创建features目录,并为场景的 Python 实现创建steps子目录。创建一个新的 Gherkin 功能文件features/Auth.feature和一个新的 Python 步骤文件features/steps/Auth.py。

现在,使用Gherkin功能测试语言将您的测试场景添加到Auth.feature :
功能:Auth 场景:未经身份验证的用户无法访问该页面 如果我没有通过身份验证,当我访问该页面时,状态码是 302 场景:经过身份验证的用户可以访问该页面 如果我通过了身份验证,当我访问该页面时,状态码是 200
在features/steps/Auth.py Python 文件中实现Auth.feature场景中使用的步骤:
from behavior import * from django.contrib.auth.models import User use_step_matcher("re") @given("I am not authenticated") def step_impl(context): pass @when("I access the page") def step_impl( context): context.response = context.test.client.get("/") @then("状态码是 (?P<status>\d+)") def step_impl(context, status): code = context.response .status_code assert code == int(status), "{0} != {1}".format(code, status) @given("I am authenticated") def step_impl(context): user = User.objects.create_superuser (“简”,“简@example.org”,“123”)context.test.client.force_login(用户)
修改views.py文件和urls.py文件以添加我们的测试示例所需的代码:
视图.py
from django.contrib.auth.decorators import login_required from django.http import HttpResponse # 在此处创建您的视图。@login_required def show_user(request): return HttpResponse("OK")
网址.py
from django.urls import path from Django_Behave import views urlpatterns = [ path('', views.show_user), ]
现在,实现关键调整:添加'behave_django'
到settings.pyINSTALLED_APPS
的部分。

完成此操作后,您的应用程序就可以进行测试会话了。您只需要为您的场景运行测试配置。
在编辑器窗口中打开Auth.feature文件。将光标放在包含任何语句的行上,然后右键单击它,然后选择Run <scenario name>。预览测试运行结果。Scenario

从测试报告中,您可以了解到测试是由manage.py运行的。您还可以查看场景的多少步骤已通过、失败或跳过。