Im writing some code which retrieves info about installed apps, especially defined models, and then does stuff based on that information, but Im having some problems writing a clean, nice unittest. Is there a way to emulate or add an app in unittests without have to run manage.py startproject, manage.py startapp in my testsfolder to have a test app available for unittests?
I m writing some code which retrieves info about installed apps, especially defined models,
Share
Sure, try this on for size:
Your test case would look something like this:
In case you were wondering why, I did an override of
_pre_setup()and_post_teardown()so I don’t have to bother with callingsuper()insetUp()andtearDown()in my final test case. Otherwise, this is what I pulled out of Django’s test runner. I whipped it up and it worked, although I’m sure that, with closer inspection, you can further optimize it and even avoid callingsyncdbevery time if it won’t conflict with future tests.EDIT:
So I seem to have gotten out of my way, thinking you need to dynamically add new models. If you’ve created an app for testing purposes only, here’s what you can do to have it discovered during your tests.
In your project directory, create a
test.pyfile that will contain your test settings. It should look something like this:You can now run your tests with
python manage.py test --settings=myproject.testand your app will be in the installed apps.