【发布时间】:2011-11-11 13:20:34
【问题描述】:
我有一些特殊情况需要在 django 中进行测试。我正在尝试通过编写自己的测试用例来扩展现有的 django 测试。这是我目前的做法。
from django.tests import TestCase
# define my own method as a function
def assertOptionsEqual(self, first, second):
# logic here
pass
# Attach the method to the TestCase class. This feels inelegant!
TestCase.assertOptionsEqual = assertOptionsEqual
# tests go here
class KnownGoodInputs(TestCase):
def test_good_options(self):
self.assertOptionsEqual(...)
虽然这可行,但将方法定义为以self 作为第一个参数的函数,然后将其附加到TestCase 感觉不优雅。有没有更好的方法来用我自己的方法扩充 TestCase 类?我可以做到这一点...
class MyTestCase(TestCase):
def assertOptionsEqual(self, first, second):
...
并使用MyTestCase 进行所有测试,但想知道是否有更好的选择。谢谢!
【问题讨论】:
-
子类化并使用另一个方法名怎么样?
标签: python class inheritance methods monkeypatching