2012-05-22 1 views
4

일부 사례가 동적으로 추가되는 불필요한 TestCase를 설정하고 싶습니다. 메서드는 내 testnothing에서 표시된대로 추가되지만, unittest는 하나의 테스트 만 실행하므로 계정에 반영하지 않습니다. 너무 늦게 test_xxxx를 빌드하고 계정에 포함되지 않은 것입니다. setUpClass가 게임에서 늦게 실행됩니까? 이 방법을 __init__에 작성하고 super().__init__을 호출해야하나요?파이썬 unittest에 동적으로 테스트를 추가하는 방법

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) 

감사합니다.

답변

4

문제가 인스턴스화하기 전에 유닛 테스트에서 로더는 당신이 당신의 방법, __new__, __init__setUpClass는 ... 방법이 얻을를 만들 경우 때문에, 그것은 중요하지 않습니다, 클래스의 디렉토리()를 실행한다는 것입니다 너무 늦게 창조되었습니다.

이 문제를 해결하려면 직접 실행() 메서드를 작성하거나 메타 클래스를 사용하는 두 가지 방법이 있습니다. 전자는 이미 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) 
+0

파이썬 2.x에서 작동하게하는 방법은 무엇입니까? – SWAPYAutomation

+2

@SWAPYAutomation 클래스 C (SC, 메타 클래스 = MC) 대신 클래스 C (SC) : __metacass__ = MC' – mehtunguh

+0

또는 6과 클래스 C (six.with_metaclass (SC))를 사용합니다. – podshumok

관련 문제