Django TestCase在setUp()

时间:2018-02-15 19:52:21

标签: django django-testing

下面的代码旨在让以编程方式创建的测试运行,但不会发生。

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视图测试。

1 个答案:

答案 0 :(得分:0)

你可以尝试按如下方式运行测试...这只是演示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")