Reputation: 21
In a testing class and I want to get all the objects of a given type; this always give an empty set:
from Dictionnaire.models import Entree
class Test(TestCase):
def setUp(self):
...
Q=Entree.objects.all()
print(Q.count()) <------always get 0.
Why ?
Upvotes: 1
Views: 99
Reputation: 2026
You can dump you database into a fixture and then load that from your test database:
A fixture is a collection of data that Django knows how to import into a database. The most straightforward way of creating a fixture if you’ve already got some data is to use the
manage.py dumpdata
commandFixtures can be written as JSON, XML or YAML (with PyYAML installed) documents.
Loading data is easy: just call
manage.py loaddata <fixturename>
, where is the name of the fixture file you’ve created
And then from SetUp()
in test.py
:
from django.core.management import call_command
call_command("loaddata", "' + 'fixturefile.json' + '",
verbosity=0)
However, in order to keep your test database up to date with your production database (which I wouldn't recommend) you'll have to set up a cron job or something.
Sources:
https://stackoverflow.com/a/48737566/5094841
https://django-testing-docs.readthedocs.io/en/latest/fixtures.html
Upvotes: 0
Reputation: 20702
The idea of running tests is to have a reproducible situation each time a test is run. So a TestCase
will create a new, empty database each time it's initialised by running all your migrations first. This way you can be sure that each time you run your tests, you have the same situation.
Therefore a TestCase
does not use your development database, nor does it use your development server (runserver
). It runs completely in its own 'world'.
If you want to make sure you have some data in your database when running a test, override the class method setUpTestData()
, which is faster than doing it for every test in setUp()
.
Upvotes: 1