I started writing tests for my django app and I wondered is there a way to test, some functionalities that are the same in more than one model, at the same time. For example if I want to test the __unicode__()
method, which comes up in all of my classes, and instead of writing a test for every single model, would it be possible to optimize it and test it once for all models?
Asked
Active
Viewed 85 times
0

Code4fun
- 121
- 1
- 7
-
https://docs.pytest.org/en/latest/parametrize.html – allcaps Apr 11 '17 at 13:04
2 Answers
0
I think that it is possible but I would prefer doing this in seperate unit_tests in seprerate TestModels testcases. I think that more tests is a better approach because if you change a method in your app in the future you going to need to change only one test. If you have only one test for all models then you are going to need to:
- fix the group test
- write another test to handle one model
Which in my opinion is a waste of time.
The first idea that comes to my mind is that you import all your models and pack them in a list, then you could just use the for loop to execute the methods. Just do something like this
from app.models import Model1, Model2, Model3
models_list = [Model1,Model2,Model3]
for mod in models_list:
mod.method()

Dawid Dave Kosiński
- 841
- 1
- 7
- 21
0
According to this answer, you can do something like:
from django.db.models import get_app, get_models
# In your test method:
app = get_app('my_application_name')
for model in get_models(app):
assert unicode(model(something='something')) == u'expected unicode'

Community
- 1
- 1

alfonso.kim
- 2,844
- 4
- 32
- 37
-
sadly this solution is depricated. I tried using `from django.apps import apps` and `for model in apps.get_model():` however I had 0 luck – Code4fun Apr 19 '17 at 09:28