Django中测试断言的可重用助手

时间:2014-05-29 19:06:13

标签: python django

我正在为Django 1.4应用程序编写单元测试。在我的tests.py中,我希望有一个可以在我的测试类中使用的辅助函数。帮助器定义如下:

def error_outcome(self, response):
    self.assertEqual(response.status_code, 403)
    data = json.loads(response._get_content())
    self.assertEquals(data, {'error': 1})

以下是使用帮助程序的示例测试类:

class SomeTest(TestCase):
    def test_foo(self):    
        request = RequestFactory().post('/someurl')
        response = view_method(request)
        error_outcome(self, response)

这是有效的,但它不好,因为帮助器不应该使用self,因为它是一个函数,而不是一个方法。如何在没有自我的情况下完成这项工作的任何想法感谢。

1 个答案:

答案 0 :(得分:2)

使用error_outcome()方法定义基础测试用例类:

class BaseTestCase(TestCase):
    def error_outcome(self, response):
        self.assertEqual(response.status_code, 403)
        data = json.loads(response._get_content())
        self.assertEquals(data, {'error': 1})

class SomeTest(BaseTestCase):
    def test_foo(self):    
        request = RequestFactory().post('/someurl')
        response = view_method(request)
        self.error_outcome(response)
相关问题