2017-04-11 60 views
0

我开始为我的django应用程序编写测试,我想知道是否有一种测试方法,同时在多个模型中有相同的功能。例如,如果我想测试所有类中出现的__unicode__()方法,而不是为每个模型编写测试,那么是否可以对所有模型进行优化并对其进行一次测试?用一个测试用例测试所有的django模型

+0

https://docs.pytest.org/en/latest/parametrize.html – allcaps

回答

0

我认为这是可能的,但我更愿意在seprerate TestModels测试用例中单独使用unit_tests来做这件事。我认为更多的测试是更好的方法,因为如果您将来在应用程序中更改某种方法,则只需更改一个测试。如果您对所有型号,然后你将只需要一个测试:

  1. 修复组测试
  2. 编写另一个测试来处理一个模型

这在我看来是一种浪费的时间。

我想到的第一个想法是,您导入所有模型并将它们打包在一个列表中,然后您可以使用for循环来执行这些方法。只是这样做

from app.models import Model1, Model2, Model3 

models_list = [Model1,Model2,Model3] 

for mod in models_list: 
    mod.method() 
0

this answer,你可以这样做:

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' 
+0

可悲的是这种解决方案depricated。我尝试使用'从django.apps导入应用程序'和'在apps.get_model()模型:'但是我有0运气 – Code4fun

相关问题