I have some models that have managed=False
. because of this, my tests fail due to not being able to find tables
I've followed this link https://dev.to/patrnk/testing-against-unmanaged-models-in-django and then https://github.com/henriquebastos/django-test-without-migrations to set up a custom test runner.
The runner does run, but i still run into the same problem, and I don't know why.
My django version is 2.1
How do I test when managed=False
?
The issue - is that Django wants the migrations to be there!
But this is an unmanaged model - so it doesn't have migrations! Hence, you've got issues. Yes, there are things you should do like adding a setting
that you check for to see if you're under test or not, something like this:
class Meta(object):
db_table = 'your_db_table'
managed = getattr(settings, 'UNDER_TEST', False)
In my settings.py
I have a variable called UNDER_TEST
# Create global variable that will tell if our application is under test
UNDER_TEST = (len(sys.argv) > 1 and sys.argv[1] == 'test')
This will check to see if test is an argument in the command (which it is when testing) so it will set UNDER_TEST
to True
when testing and Django will treat it as a managed model (so you will see errors that the tables don't exist)... so...
What you can try (that I find that works well) is django-pytest
, which is a way to bring pytest
into django quite easily. django-pytest
is much more up to date and kept modern (and it uses pytest
behind the scenes - which is full fleshed out and awesome in it's own right).
The nice part? You can run it with a --no-migrations
flag and then it will read over the unmanaged model (that doesn't have tables) and temporarily create those tables (based on the model) for that test without erroring out like you have seen.
This will allow you to write tests for that model like you would all your other managed models and no longer have to worry that unmanaged models might be a problem in your application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With