【问题标题】:Django TestCase creating new test_ functions with exec and setattr in setUp()Django TestCase 在 setUp() 中使用 exec 和 setattr 创建新的 test_ 函数
【发布时间】: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, exceptyield 中运行 for 循环的内部,如果有错误的话

标签: django django-testing


【解决方案1】:

您可以尝试按如下方式运行测试...这只是证明 for 循环可以打印回溯...我认为使用您的字符串方法 test_ 并尝试对 python 说它的函数不起作用...

import traceback
from django.test import TestCase

class MyTest(TestCase):

    def test_views(self):

        any_error = False
        for url in range(0, 3):
            try:
                print("running: " + str(url))
                # run my test here
                # ...
                self.assertTrue(False) # fail on purpose

            except Exception as e:
                print(str(e))
                any_error = True
                traceback.print_exc()

        if any_error is True:
            raise RuntimeError("some test fails")

【讨论】:

  • 好主意。我尝试了 setUpClass 和 setUpTestData。都没有用。
  • 我编辑了我的答案,我认为你目前使用 str_function 的方法行不通
猜你喜欢
  • 2017-10-04
  • 1970-01-01
  • 1970-01-01
  • 2011-12-08
  • 2019-09-04
  • 2019-11-29
  • 1970-01-01
  • 2020-02-16
  • 2017-09-21
相关资源
最近更新 更多