在unittest.TestCase类上使用装饰器后,不使用unittest.TestLoader()加载测试

时间:2015-04-20 15:48:45

标签: python selenium selenium-webdriver decorator python-unittest

我有一个测试作为unittest.TestCase的子类,我使用装饰器。

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:%s@ondemand.saucelabs.com: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"。问题来自哪里?

1 个答案:

答案 0 :(得分:0)

你的装饰者正在改变它正在装饰的物体的签名。 Graham Dumpleton非常详细地解释了这个问题here。尝试使用pypi中的Decorator来装饰你的装饰器,使其保留其装饰的签名。