1

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 ?

Daniel Holmes
  • 1,952
  • 2
  • 17
  • 28
  • 3
    You need to create the objects in your database first: a `TestCase` runs with a fresh empty database each time. – dirkgroten Apr 11 '19 at 10:04

2 Answers2

1

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().

dirkgroten
  • 20,112
  • 2
  • 29
  • 42
  • My problem is that I want to make tests on objects in my real data base; I have a collection (Entree is the script) and for each of these objects, I compute an URL, and I want to test if this URL is ok, can be attained. It seems that I cannot do that directly in Django's test framework ? – Thierry Dumont Apr 11 '19 at 13:13
  • And you can't test that by loading a fixture with the required data at the beginning of the test? You can `dumpdata` from your real database and use that as fixtures. – dirkgroten Apr 11 '19 at 13:16
  • If you want to test against a remote server (e.g. if you have a pre-production server to test), use a different framework, e.g. selenium. Don't run any tests on your production environment, that's really dangerous! – dirkgroten Apr 11 '19 at 13:27
  • Yes, Selenium seems very interesting. Thanks! – Thierry Dumont Apr 11 '19 at 16:49
0

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 command

Fixtures 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

VnC
  • 1,936
  • 16
  • 26