12π
Out of the box, pytest
doesnβt know about the Django database, even with pytest-django
installed. Never fear, though: pytest-django
makes it easy for your tests to access the Django database using its django_db pytest mark.
Give this a try:
import pytest
@pytest.mark.django_db
def test_was_published_recently_with_future_question():
time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=time)
assert future_question.was_published_recently() is False
7π
I had a similar problem when invoking tests either with pytest
or python setup.py test
.
For pytest
invocation installing pytest-django
in my virtual env solved the problem.
For python setup.py install
adding pytest-django
to the tests_require
argument of setup()
solved it.
Hereβs the snippet of setup.py
:
TEST_REQUIREMENTS = [
'pytest',
'pytest-django',
'pylint',
'pylint_django',
'git-pylint-commit-hook',
]
setup(
name='foo',
version='0.0.1',
description='Foo package',
author='...',
author_email='...',
packages=['foo'],
install_requires=INSTALL_REQUIREMENTS,
setup_requires=SETUP_REQUIREMENTS,
tests_require=TEST_REQUIREMENTS,
)
- "TemplateSyntaxError Invalid block tag: 'trans'" error in Django Templates
- Gunicorn sync workers spawning processes
- Exclude field from values() or values_list()
5π
According to Django: AppRegistryNotReady(), when not using manage.py
one must call django.setup()
explicitly. I verified this by running the pytest
test from a manage.py
shell:
Kurts-MacBook-Pro:mysite2 kurtpeek$ python3 manage.py shell
Python 3.6.3 (v3.6.3:2c5fed86e0, Oct 3 2017, 00:32:08)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.
In [1]: import pytest
In [2]: pytest.main('polls/tests.py')
================================= test session starts ==================================
platform darwin -- Python 3.6.3, pytest-3.2.3, py-1.4.34, pluggy-0.4.0
rootdir: /Users/kurtpeek/Documents/Scratch/mysite2, inifile: pytest.ini
plugins: timeout-1.2.1
collected 1 item
polls/tests.py F
======================================= FAILURES =======================================
___________________ test_was_published_recently_with_future_question ___________________
def test_was_published_recently_with_future_question():
time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=time)
> assert future_question.was_published_recently() is False
E assert True is False
E + where True = <bound method Question.was_published_recently of <Question: >>()
E + where <bound method Question.was_published_recently of <Question: >> = <Question: >.was_published_recently
polls/tests.py:18: AssertionError
=================================== warnings summary ===================================
None
passing a string to pytest.main() is deprecated, pass a list of arguments instead.
-- Docs: http://doc.pytest.org/en/latest/warnings.html
========================= 1 failed, 1 warnings in 0.14 seconds =========================
Out[2]: 1
This is not really an acceptable solution, however, as the tests need to be runnable from the command line. Are there perhaps other pytest
decorators to ensure the required setup?
- Django test: TransactionManagementError: You can't execute queries until the end of the 'atomic' block
- Django render_to_string() ignores {% csrf_token %}
- Is the Global Request variable in Python/Django available?
- How to unit test methods inside django's class based views?
1π
For me, setting the DJANGO_SETTINGS_MODULE as an export on the command line or in the pytest.ini solved the problem.
It seems to ignore the export of that env var in conftest.py
If I figure it out I will update this post.
- Select Children of an Object With ForeignKey in Django?
- Tag inside tag in django template
- Succinct way of updating a single field of a django model object
- What is the difference between a Multi-table inherited model and a simple One-to-one relationship between the same two models?
- Django template indentation guideline
0π
Does it say somewhere in the docs that the test should work without subclassing django.test.TestCase
? I donβt think that django-pytest
does anything special in regards to loading django apps. So, if your class continues to inherit from TestCase
, you should be able to use everything else from pytest
, such as itβs assertions, fixtures, etc.
0π
Just by installing pytest-django
in addition to existing pytest
, the error was gone for me as well π
- Django: How to keep the test database when the test is finished?
- How do I restrict access to admin pages in Django?
- How to get field names when running plain sql query in django
0π
For me the issue was that I forgot to add pytest.ini
to link pytest
to my project settings β see the docs
# -- FILE: pytest.ini (or tox.ini)
[pytest]
DJANGO_SETTINGS_MODULE = test.settings
# -- recommended but optional:
python_files = tests.py test_*.py *_tests.py
- Can not use celery delay for saved form: object is not JSON serializable
- How to render a Django form with RadioSelect without getting a checked radiobutton by default?
- Django error: [<class 'decimal.InvalidOperation'>]
0π
When trying to run pytest without starting up django, you might encounter this kind of issue.
To resolve the Apps aren't loaded yet
error, I made the following changes:
-
Created a
test_settings.py
file: I created a new file named test_settings.py in the config directory of my Django app with the same content from mysettings.py
. -
Imported
django
module and addeddjango.setup()
in thetest_settings.py
after other module imports and startup configurations.
This allowed me to initialize the Django app registry and other necessary components before running the tests.
Hereβs how the test_settings.py
file looks:
# test_settings.py
import django
... (other module imports and configurations)
django.setup()
By adding these two lines, the Apps aren't loaded yet
error was resolved, and I was able to run my tests using pytest without any issues.
Hereβs my project structure:
.
βββ Dockerfile
βββ app
βΒ Β βββ config
βΒ Β βΒ Β βββ __init__.py
βΒ Β βΒ Β βββ asgi.py
βΒ Β βΒ Β βββ celery.py
βΒ Β βΒ Β βββ celery_beat_schedules.py
βΒ Β βΒ Β βββ settings.py
βΒ Β βΒ Β βββ test_settings.py
βΒ Β βΒ Β βββ urls.py
βΒ Β βΒ Β βββ wsgi.py
βΒ Β βββ core
βΒ Β βΒ Β βββ __init__.py
βΒ Β βΒ Β βββ admin.py
βΒ Β βΒ Β βββ apps.py
βΒ Β βΒ Β βββ constants.py
βΒ Β βΒ Β βββ decorators.py
βΒ Β βΒ Β βββ enums.py
βΒ Β βΒ Β βββ management
βΒ Β βΒ Β βΒ Β βββ __init__.py
βΒ Β βΒ Β βΒ Β βββ commands
βΒ Β βΒ Β βΒ Β βββ __init__.py
βΒ Β βΒ Β βΒ Β βββ wait_for_db.py
βΒ Β βΒ Β βββ models.py
βΒ Β βΒ Β βββ services.py
βΒ Β βΒ Β βββ tests
βΒ Β βΒ Β βΒ Β βββ factories.py
βΒ Β βΒ Β βΒ Β βββ models
βΒ Β βΒ Β βΒ Β βΒ Β βββ test_kr.py
βΒ Β βΒ Β βΒ Β βββ views
βΒ Β βΒ Β βΒ Β βββ test_search_member.py
βΒ Β βΒ Β βββ urls.py
βΒ Β βΒ Β βββ views.py
βΒ Β βββ manage.py
βΒ Β βββ pytest.ini
Additional Note:
Itβs important to ensure you have the pytest
and pytest-django
packages installed.
- How to filter filter_horizontal in Django admin?
- What does "Directory indexes are not allowed here." mean in a Django error?
0π
inspired by the answer above by @Peter Varshavsky
I had pytest installed, but invoking pytest
was giving that error.
so installed pytest-django
, then i created a pytest.ini
file in the root directory with
[pytest]
DJANGO_SETTINGS_MODULE = projectname.settings
it also works if you just export the variable before running the command pytest
.
now if i invoke pytest
, it works succeussfully.
- Signing in leads to /accounts/profile/ in Django
- Can't git-push to heroku due to "Build stream timed out"
0π
In the conftest.py file made the following changes before importing any other models / files.
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "<MODULE_NAME>.settings")
import django
django.setup()
The above snippets helped me to resolve the issue for me.
- Django_rest_swagger β 'staticfiles' is not a registered tag library. Must be one of:
- How do I write a single-file Django application?
- What is query.clone(), queryset.clone() for in django?
- Multiple lookup_fields for django rest framework