【发布时间】:2018-02-15 19:52:21
【问题描述】:
下面的代码旨在让以编程方式创建的测试运行,但没有发生。
class TestAdminGetViews(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.admin_user = models.UserManager.create_user(email='test@test.com',password='12387343ad!'
,user_type=utils.UserTypes.admin.name)
self.client = Client()
#create the test methods programmatically where URLNames.object.name = view.name
for url in utils.URLNames: #an Enum object
#is there a view associated with with this URLName?
if callable(getattr(views,url.name)):
#placeholder code just to see if tests run
str_function = '''def test_{}(self):\n\tself.assertIs(True,True)\nglobal my_function\nmy_function = test_{}'''.format(url.name, url.name)
exec( str_function )
print( my_function )
setattr(self,'test_' + url.name,my_function)
#factory, admin_user, client and all the functions show themselves
#as being attached to self
print(str(self.__dict__))
打印函数显示代码运行“成功”。字典包含 factory、admin_user 和 client,所有这些都可以在硬编码的 test_ 函数中访问。以编程方式创建的函数也以正确的名称和函数名称显示在字典中。
但是,Django 测试环境不运行以编程方式创建的函数。为什么?
一点背景色: 我的上一个分段部署在 GET 请求方面存在未检测到的问题。我想在未来通过测试避免那些简单的错误。我不想为每个视图编写一个新的 test_function(),而是想以编程方式创建 GET 视图测试。
【问题讨论】:
-
为什么需要首先创建 test_?您的带有许多测试选项的 for 循环可以在单个测试中运行_
-
因为在多次失败的情况下,我只会得到第一次失败的报告。另外,我意识到我应该在 setUpTestData(cls) 中运行此代码,但我仍然遇到同样的问题。
-
你可以在
try, except和yield中运行 for 循环的内部,如果有错误的话
标签: django django-testing