-1

我有一個測試,作爲unittest.TestCase的一個子類,我使用裝飾器。在我的unittest.TestCase類上使用裝飾器後,未使用unittest.TestLoader()加載測試

import unittest 
from selenium import webdriver 
import sys 

SAUCE_USERNAME = 'xxx' 
SAUCE_ACCESS_KEY = 'xxx' 
sauce = SauceClient(SAUCE_USERNAME, SAUCE_ACCESS_KEY) 
browsers = [{"platform": "Mac OS X 10.9", 
    "browserName": "chrome", 
    "version": "31"}, 
    {"platform": "Windows 8.1", 
    "browserName": "internet explorer", 
    "version": "11"}] 


def on_platforms(platforms): 
    def decorator(base_class): 
     module = sys.modules[base_class.__module__].__dict__ 
     for i, platform in enumerate(platforms): 
      d = dict(base_class.__dict__) 
      d['desired_capabilities'] = platform 
      name = "%s_%s" % (base_class.__name__, i + 1) 
      module[name] = new.classobj(name, (base_class,), d) 
    return decorator 

@on_platforms(browsers) 
class MyTestSuite(unittest.TestCase): 
    @classmethod 
    def setUpClass(cls): 
     cls.desired_capabilities['name'] = cls.id() 
     sauce_url = "http://%s:%[email protected]:80/wd/hub" 
     cls.driver = webdriver.Remote(
     desired_capabilities=cls.desired_capabilities, 
     command_executor=sauce_url %  (SAUCE_USERNAME,SAUCE_ACCESS_KEY)) 
    cls.driver.implicitly_wait(30) 

def test_1from_sauce(self): 
    pass 

def test_2from_sauce(self): 
    pass 

@classmethod 
def tearDownClass(cls): 
    cls.driver.quit() 

if __name__ == "__main__": 
    suite =unittest.TestLoader().loadTestsFromTestCase(Registration) 
    unittest.TextTestRunner(verbosity=1).run(suite) 

問題是,當我使用CLI運行此代碼,我得到這個錯誤:

File "MyTestSuite.py", line xxx, in <module> 
    suite = unittest.TestLoader().loadTestsFromTestCase(Registration) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/loader.py", line 50, in loadTestsFromTestCase 
    if issubclass(testCaseClass, suite.TestSuite): 
TypeError: issubclass() arg 1 must be a class 

這個錯誤消失,當我註釋掉@on_platforms裝飾。另外當我使用這個裝飾器時,MyTestSuite type is "Nonetype",當我刪除它時,MyTestSuite的類型更改爲"type"。問題來自哪裏?

回答

0

你的裝飾器正在改變它裝飾物體的簽名。格雷厄姆·杜姆普爾頓極其詳細地解釋了這個問題here。嘗試使用來自pypi的Decorator來裝飾你的裝飾器,使其保留它裝飾的簽名。