Enabling support for behave-django
With PyCharm you can benefit from the behavior-driven development (BDD) with Django by enabling behave-django integration in your Django applications.
To enable behave-django integration:
- In your Django project, install the following Python packages:
behave
behave-django
- Modify the structure of your project to meet the behave structural requirements. In your Django application directory, create the
features
directory for the test scenario files and thesteps
subdirectory for the Python implementations of the scenarios. Create a new Gherkin feature file,features/Auth.feature
, and a new Python step file,features/steps/Auth.py
. -
Now, add your test scenarios to the
Auth.feature
by using Gherkin feature testing language:Feature: Auth Scenario: Unauthenticated user can't access the page Given I am not authenticated When I access the page Then Status code is 302 Scenario: Authenticated user can access the page Given I am authenticated When I access the page Then Status code is 200
-
Implement the steps used in the
Auth.feature
scenarios in thefeatures/steps/Auth.py
Python file:from behave 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("Status code is (?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("jane", "jane@example.org", "123") context.test.client.force_login(user)
-
Modify the
views.py
file and theurls.py
files to add code required for our testing sample:views.py
from django.contrib.auth.decorators import login_required from django.http import HttpResponse # Create your views here. @login_required def show_user(request): return HttpResponse("OK")
urls.py
from django.urls import path from Django_Behave import views urlpatterns = [ path('', views.show_user), ]
- Now, implement the key tweak: add
'behave_django'
to theINSTALLED_APPS
section of thesettings.py
. With this done, your application is ready for a test session. All you need is to run test configurations for your scenarios. - Open the
Auth.feature
file in the Editor window. Position the cursor on a line with any of theScenario
statements, then right-click it, and choose Run <scenario name>. Preview the test run results. From the test report, you can learn that the test was run bymanage.py
. You can also see how many steps of the scenario have been passed, failed, or skipped.
Last modified: 23 July 2018