[Django]-Django tests with selenium not loading fixtures

2đź‘Ť

âś…

Django testing with Selenium can be touchy. To recap, there are three main issues you have to deal with to get tests like this to work:

1) Selenium needs a running Django server to bounce requests off of.

2) Your running Django server should be connected to the test database.

3) TestCase tests run in a transaction. Since the running Django server can’t see into the test case’s transaction, any fixtures you load will be completely invisible/inaccessible to Selenium (source: Lara’s link, qris’s answer).

Solution:
To solve the first two problems, you need a testing-specific settings file. In it, you need to define a default database that points to your testing database, and you need to give your testing database’s settings so that the names match (See the example in my question). When you plan to run your tests, you need to run a Django development server and your tests using the testing settings file.

To solve the third problem, use TransactionTestCase instead of TestCase. TransactionTestCase is meant to give developers finer control over transaction behavior during testing, so it doesn’t automatically run everything inside of a transaction (which, in turn, gives the running server instance access to fixtures). Even though this isn’t exactly what we’re trying to do in this case, the result is that the tests work and clean up after themselves automatically.

Note: You should probably consider separating black-box and white-box tests from each other. This keeps your Django tests “vanilla” so future developers don’t have to waste as much time figuring out why Django documentation doesn’t seem to apply in all cases. It also decouples functional tests from the unit tests, which is good in cases where a developer on your team doesn’t have access to Selenium (or a compatible version of Selenium) on their machine, or when you want to run only the unit tests or functional tests, but not both. You would need to manually set up your testing environment to suit your needs, but I believe this would keep the testing code cleaner in the long run.

Thanks to Lara for pointing me in the right direction on this.

👤Adam

1đź‘Ť

Once I had the same problem and, I noticed that somehow, Django Test Case and Selenium don’t use the same database. Why? I have no clue!

I think is something about tearDown and Setup … Anyway, I think you can solve your problem here -> How to have Django test case and Selenium server use same database?

👤Lara

Leave a comment