首页 > 解决方案 > Python - 将参数传递给从 TestCase 继承的基类

问题描述

我有一些代码用于使用 Python 运行一些硒测试。

我创建了一个继承自 TestCase 的基类,一切正常。但是,我希望能够访问传递给基类的配置对象,以便我可以引用 chromedriver 可执行路径以及是否无头运行测试。

class TestBase(unittest.TestCase):

    def setUp(self):
        chrome_options = webdriver.ChromeOptions()
        is_headless = bool(distutils.util.strtobool(self.config.get("CHROMEDRIVER", "headless_enabled")))
        if is_headless:
            chrome_options.headless = True
        else:
            chrome_options.headless = False

        executable = self.config.get("CHROMEDRIVER", "executable_path")
        self.driver = webdriver.Chrome(executable, options=chrome_options)


class TestWebSite(TestBase):

    def setUp(self):
        root_dir = os.path.abspath('../../')
        self.config = ConfigLoader(root_dir + '/resources/config.ini').config
        super().setUp()

    def test_tc001_test_page_loads(self):
        pass


class ConfigLoader:
    def __init__(self, config_file):
        self.config = configparser.ConfigParser()
        if os.path.exists(config_file):
            self.config.read(config_file)
        else:
            raise SystemExit('Could not find config file to load.')

我在 TestWebSite 类中定义 self.config ,该类有效,尽管当我在 PyCharm 中查看带有以下警告的标志时:unresolved attribute reference 'config' for class 'TestBase',毫不客气地因为我没有通过构造函数。

解决这个问题的最佳方法是什么?

我可以将配置加载移动到基类中,但更喜欢在测试用例级别使用它。

标签: pythonseleniumunit-testingwebdrivertestcase

解决方案


推荐阅读