[英]how to add tests dynamically to python unittest
我想建立一個unittest
,其中一些案件動態添加的TestCase。 這些方法是添加的,如我的test_nothing
所示,但是, unittest
不考慮它們,因為它只運行一個測試。 就像我構建我的test_xxxx
太晚了,他們沒有看到。 setUpClass
在游戲中執行得太晚了嗎? 我應該把它放在__init__
構建我的方法中,然后調用super().__init__
嗎?
import unittest
import blognodes
class Test_base62(unittest.TestCase):
testset = { 0: '0', 10: 'a', 61: 'Z', 62: '10', 3844: '100'}
@classmethod
def setUpClass(cls):
cls.testme = 5
print("i am the setUp function")
for d, b62 in cls.testset.items():
print("building the first set")
cls.build_test_base62_values(d, b62)
print("building the second set")
cls.build_test_int_values(d, b62)
@classmethod
def build_test_base62_values(cls, d, b62):
def f(cls):
target = blognodes.base62(d)
cls.assertEqual(target.str(), b62)
fname = "test_base62_value_{}".format(d)
setattr(cls, fname, f)
@classmethod
def build_test_int_values(cls, d, b62):
def f(cls):
target = blognodes.base62(d)
cls.assertEqual(target.int(), d)
fname = "test_int_value_{}".format(d)
setattr(cls, fname, f)
def test_nothing(self):
print("i'm test nothing")
t = dir(self)
print(t)
self.assertEqual(5, self.testme)
謝謝。
問題是 unittest 的加載器在實例化它之前在類上運行 dir() ,因此,在何處創建方法、 __new__
、 __init__
、 setUpClass
……這些方法創建得太晚了。
有兩種方法可以解決這個問題,編寫自己的 run() 方法,或使用元類。 前者意味着您必須重新編寫已經在 unittest 中編寫的發現。 元類實際上實現起來並不復雜。 這是我所做的:
import unittest
import blognodes
class meta_Test_base62(type):
testset = { 0: '0', 10: 'a', 61: 'Z', 62: '10', 3844: '100'}
@classmethod
def __prepare__(mcls, name, bases):
d = dict()
d['testme'] = 5
for b10, b62 in mcls.testset.items():
fname = "test_base62_value_{}".format(b10)
d[fname] = mcls.build_test_base62_values(b10, b62)
fname = "test_int_value_{}".format(b10)
d[fname] = mcls.build_test_int_values(b10, b62)
return d
@classmethod
def build_test_base62_values(cls, b10, b62):
def f(self):
target = blognodes.base62(b10)
self.assertEqual(target.str(), b62)
return f
@classmethod
def build_test_int_values(cls, b10, b62):
def f(self):
target = blognodes.base62(b10)
self.assertEqual(target.int(), b10)
return f
class Test_base62(unittest.TestCase, metaclass=meta_Test_base62):
def test_nothing(self):
self.assertEqual(5, self.testme)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.