我正在为 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,因为它是一个函数,而不是一个方法。关于如何在没有 self 的情况下完成这项工作的任何想法?谢谢。
请您参考如下方法:
使用定义的 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)
