如何在Python中使用装饰器运行测试跨平台/浏览器?

时间:2015-04-17 22:14:15

标签: python selenium parallel-processing cross-platform saucelabs

我有一个测试套件如下:

import unittest
from selenium import webdriver

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__":
     unittest.main()

我的目标是为浏览器中的浏览器/平台运行test_1from_sauce和test_2from_sauce,而且我确实希望在setUpClass上设置的浏览器中连续执行这两个操作。为了解释更多,我想打开一个浏览器并进行两个测试然后退出该驱动程序并启动另一个驱动程序。

现在,当我运行此代码时,我收到此错误: TypeError:unbound方法setUpClass()必须使用SeleniumSauce_2实例作为第一个参数调用(没有任何替代)

我知道应该在类和子类声明中进行修改,但我不知道应该做什么或者应该更改哪个部分。

编辑:我省略了以下行,它运行良好:

cls.desired_capabilities['name'] = cls.id()

1 个答案:

答案 0 :(得分:2)

您在问题中显示的代码缺少sysnew的导入。其次,在添加正确的导入后运行代码时出现的错误不是您在问题中报告的错误,而是:

EE
======================================================================
ERROR: setUpClass (__main__.MyTestSuite_1)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "tests.py", line 33, in setUpClass
    cls.desired_capabilities['name'] = cls.id()
TypeError: unbound method id() must be called with MyTestSuite_1 instance as first argument (got nothing instead)

我省略了与上述相同的第二个ERROR,除了它是MyTestSuite_2而不是MyTestSuite_1。问题很清楚。您致电id()的{​​{1}}成员,但cls实例方法而不是类方法,因此它需要一个实例上课,而不是班级本身。我不确定你最终想要的是什么,但是如果你将它用于你的id(),则错误不再发生并且尝试连接:

setUpClass

唯一的修改是方法的第一行。

顺便说一下,我不明白你使用@classmethod def setUpClass(cls): cls.desired_capabilities['name'] = cls.__name__ 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) 的原因。首先,不推荐使用new.classobj模块。其次,使用new内置而不是type工作。