如何在 python 中实现此功能?

How do I achieve this functionality in python?

我正在 py.test 编写 python 和 运行 的自动化 UI 测试。我试图让它对任何正在编写测试的人来说尽可能简单。我想要实现的是这样的。

def test_set_feature_example(self, fix_web_ui)
     A = fix_web_ui["features"]
     A.features.example = 'somestring' # What this should achieve is using selenium, set the text with the id 'features.example' with 'somestring'. 

这应该实现的是使用 selenium,将 ID 为 'features.example' 的文本设置为 'somestring'。 UI 中的 ID 与提到的相同。如果我可以覆盖运算符“=”,这是可能的。既然那是不可能的,有没有其他方法可以实现这种功能。我认为的另一种方法是在 fix_web_ui 的终结器中添加这些功能,但这行不通,因为这意味着将 fix_web_ui 限制为一个函数。有什么想法吗?希望我清楚。

在将其标记为重复之前,我并不是在询问赋值是否可以重载。我问的是一种体系结构,编写测试的人可以在其中编写类似于此的内容

A.features.example = 'somestring'

而不是

driver = webdriver.FireFox()
item  = driver.find_elements_by_id('features.example')
item.send_keys('somestring')
driver.close()

我想你可以在这里使用夹具覆盖功能http://pytest.org/latest/fixture.html#overriding-fixtures-on-various-levels

因此,如果您的 fix_web_ui 是更高级别的固定装置 (scope="session"),那么您可以在模块级别覆盖它。您的 fix_web_ui fixture 必须是可变对象。

# conftest.py

@pytest.fixture
def fix_web_ui():
    class Feature1(object):
        def __init__(self):
            self.example = "example1"
    return {"features": Feature1()}

# test_feature.py

import copy

@pytest.fixture
def fix_web_ui(fix_web_ui):
     # here it depends how you want to handle this:
     # 1) modify original fixture values - that will persist for the outer scope too
     # 2) or make a copy of a the outer scope fixture and override it's attributes like this:
     fix_web_ui2 = copy.deepcopy(fix_web_ui)
     fix_web_ui2.example = "overridden"
     return fix_web_ui2

def test_feature_functionality(fix_web_ui):
    assert fix_web_ui.example == "overridden"