I want to be able to do conditional connect() based on either I started django in testing mode or not.
in my settings.py I use mongoengine connect() method to connect to my database but the problem is that I don't want to do that if I ran manage.py test
Is there any way I can check if settings.py is being imported from tests or not, some flag maybe.
something like if not IN_TESTS: connect()
I'm solving this with a custom test runner. Here is an example I based my solution off of: https://github.com/xintron/django-mongorunner/blob/master/mongorunner/testrunner.py
This has the advantage of providing a fresh database for each of your unit tests.
I'm not sure it's completely foolproof, but I use the fact that in a test, you will have probably started it from the command line with
./manage.py test
, so 'test' is one of the command-line args. So this works:What I do is use
register_connection
, and then mock the connections on test.In the file that I define the Mongo Documents I have this:
Then in the tests I use the mock library to change the behave of connections (it would be possible too to mock one of the functions on the
connection
sub module likeget_db
) like this:While it is possible to do that, it is easier and common practice to have 2 settings files. One possible configuration could be:
You have 2 settings files,
lsettings.py
that doesn't connect andsettings.py
that doesSo, while locally testing you can:
And it doesn't connect.
tl;dr: It is easier to manage configuration differences by having multiple configuration files that import each other conditionally rather than trying to have conditional parameters within the same settings file. YMMV.