Background
I found myself having a bit of free time on Friday the 5th so I thought it would be helpful to my team to try and decrease the amount of warnings we received after running tox and having all tests pass.
Here was my environment:
Ubuntu - 20.04 LTS
django - 3.2.8
pytest - 6.2.5
pytest-django - 4.4.0
tox - 3.24.4
Warning and Resolution
I received a very strange / obscure warning whenever test databases would be torn down. The warning in full was:
Error when trying to teardown test databases: TypeError('object.__new__() takes exactly one argument (the type to instantiate)')
I ended up resolving this warning by:
- Navigating to my
pytest.ini
file in my base directory. - On the
addopts
line, adding two switches to the end:--reuse-db --create-db
.
The final version of this line looked like this:
[pytest]
// some other settings
addopts = [additional options here] --reuse-db --create-db
Findings
The source of this warning is from pytest-django's fixtures.py
file. It can be found here on GitHub . The function being called is teardown_database
which is defined on line 126.
According to pytest-django's official documentation, using the reuse-db
and create-db
switches together helps isolate and recreate databases throughout tests.
--reuse-db will not pick up schema changes between test runs. You must run the tests with --reuse-db --create-db to re-create the database according to the new schema. Running without --reuse-db is also possible, since the database will automatically be re-created.
(source: pytest-django docs)
My guess is that somewhere during the tests, not all of the test databases are properly created. This would result in pytest-django trying to tear down something that isn't there. This would also explain why it is looking for an object that can't be used when it is calling teardown_database
.
Finally, in my time spent searching for a solution, I found some similar pages online. While they weren't directly related to my problem and solution, they may be helpful in forming a trail of breadcrumbs towards solving a different problem:
SO - Why is pytest throwing an "Attribute Error: 'NoneType' object has no attribute..."
GitHub - Ignoring migrations during Django testing (unmanaged databases, legacy databases, etc)
References and Special Thanks
I want to specifically thank Cris Ewing for their article on Medium . I relied heavily on their troubleshooting and debugging methodology. Without their post, I would never have found a solution or experimented using ideas from the official pytest-django documentation. Thank you Cris!
I also wish to thank Stefaan Lippens for their short blog post on how to disable PyTest's default log capturing. It was very useful as I was debugging. It can be found here .
References:
pytest-django documentation --reuse-db reuse the test database between runs
pytest-django source code
Top comments (0)