user1724763
user1724763

Reputation:

Create model just for testing

I have an abstract User model.

The tests include subclassing this abstract model and setting AUTH_USER_MODEL to the subclassed model.

The problem with AUTH_USER_MODEL is it must be of the form "app-name.model-name" and hence it must refer to a model in a models.py file . But if it is inside a models.py file, it will get sync'ed to production database, which isn't exactly harmful but it would be nice if it isn't so.

I have seen Django: How to create a model dynamically just for testing but the answers seem hackish (and unreliable?)

Currently what I do is:

in [apps]/models.py:

# this model only gets created during a test
if 'test' in sys.argv:
    class AccountTest(AbstractAccount):
        pass 

in [apps]/tests/init.py:

@override_settings(
    AUTH_USER_MODEL = '[apps].AccountTest',
)
class AccountManagerTest(TransactionTestCase):

Does anyone have a better way? This feels rather hackish. Also, any problem with this approach?

Upvotes: 0

Views: 121

Answers (1)

ppetrid
ppetrid

Reputation: 3845

A good approach is to use separate settings file for your testing environment. You could have an application that is listed only in the INSTALLED_APPS of these test settings, and implement your test models there. This approach is also good if for example you want to use nose to run your tests etc... Then you should run your tests like this:

python manage.py test --settings=my_project.test_settings

Upvotes: 2

Related Questions