pytest
Summary #
Awesome testing framework for python.
Setting up Django project #
Create pytest.ini file in the Django root directory #
pytest.ini
[pytest]
DJANGO_SETTINGS_MODULE = epay.settings # in KFUPM settings loads local_settings
# -- recommended but optional:
python_files = tests.py test_*.py *_tests.py
Run tests #
Directory structure:
epay # repo root
epay # django root
epay
settings.py# loads local_settings.py
__init__.py
local_settings.py
app # application
tests
views_tests.py
pytest.init
conftest.py
From the repository root
pytest epay
Snippets #
Ignoring captcha(django-captcha) #
used in epay got hint from github
from unittest import mock
@mock.patch("captcha.fields.ReCaptchaField.validate")
def my_test(self, mock_function):
import pytest
from django.urls import reverse
from app.models import ClientApp
@pytest.fixture
def link_based_client_setup(admin_user):
client_app = ClientApp.objects.create(
name="MX",
payment_type="INIT211",
is_active_for_payments=True,
payment_type_description="MX description",
payment_amount=200,
redirect_url=None,
success_message="paied successfully"
)
client_app.admins.add(admin_user)
@pytest.fixture
def app_based_client_setup(admin_user):
client_app = ClientApp.objects.create(
name="Student-Transcript",
is_active_for_payments=True,
payment_type_description="Transcript Fees",
payment_amount=10,
redirect_url="https://student-transcript.edu.sa",
)
client_app.admins.add(admin_user)
@pytest.mark.django_db
class TestPaymentRequestView:
def test_get_link_based_request(self, client, link_based_client_setup):
url = reverse('payment-request')
get_params =
"client-name": "MX",
"payment-type": "INIT211",
"payer-id": "student2"
response = client.get(url, get_params)
content = response.content.decode(response.charset)
assert response.status_code == 200
assert get_params.get("client-name") in content, "Users sees confirmation form"
def test_get_link_based_request_submission(self, client, link_based_client_setup, settings, monkeypatch):
# starts here *************
def _fake_validate(obj, value):
return
monkeypatch.setattr("captcha.fields.ReCaptchaField.validate", _fake_validate)
post_data =
"client_name": "MX",
"payer_id": "123",
"payment_type": "INIT211"
url = reverse('payment-request')
response = client.post(url, post_data)
content = response.content.decode(response.charset)
assert response.status_code == 302
print(content)
Sample pytest.ini file
#
This file should be in the root or directory from where the pytest is run
```pytest.ini [pytest] DJANGO_SETTINGS_MODULE = dsr_incentives.settings
python_files = tests.py test_*.py *_tests.py ;python_files = *.py addopts = -v
norecursedirs = cycle ```