ljs*_*dev 7 python oop python-behave
使用伟大的Behave框架,但我缺乏OOP技能.
Behave有一个内置的上下文命名空间,可以在测试执行步骤之间共享对象.在初始化我的WebDriver会话之后,我继续在我的步骤之间传递它来使用它context来保存所有内容.功能很好,但正如你在下面看到的那样,除了DRY之外什么都不是.
如何/在哪里可以将这些属性添加到step_impl()或context仅一次?
environment.py
from selenium import webdriver
def before_feature(context, scenario):
"""Initialize WebDriver instance"""
driver = webdriver.PhantomJS(service_args=service_args, desired_capabilities=dcap)
"""
Do my login thing..
"""
context.driver = driver
context.wait = wait
context.expected_conditions = expected_conditions
context.xenv = env_data
Run Code Online (Sandbox Code Playgroud)
steps.py
@given('that I have opened the blah page')
def step_impl(context):
driver = context.driver
wait = context.wait
expected_conditions = context.expected_conditions
xenv = context.xenv
driver.get("http://domain.com")
driver.find_element_by_link_text("blah").click()
wait.until(expected_conditions.title_contains("Blah page"))
@given(u'am on the yada subpage')
def step_impl(context):
driver = context.driver
wait = context.wait
expected_conditions = context.expected_conditions
xenv = context.xenv
if driver.title is not "MySubPage/":
driver.get("http://domain.MySubPage/")
wait.until(expected_conditions.title_contains("Blah | SubPage"))
@given(u'that I have gone to another page')
def step_impl(context):
driver = context.driver
wait = context.wait
expected_conditions = context.expected_conditions
xenv = context.xenv
driver.get("http://domain.com/MyOtherPahge/")
Run Code Online (Sandbox Code Playgroud)
首先,你可以跳过这个解包并context在任何地方使用属性,比如context.driver.get("http://domain.com")
如果你不喜欢它并且你真的想拥有局部变量,你可以使用元组解包来使代码更好:
import operator
def example_step(context):
driver, xenv = operator.attrgetter('driver', 'xenv')(context)
Run Code Online (Sandbox Code Playgroud)
您可以将默认的属性列表分解为这样,但这会使整个事情有点隐含:
import operator
def unpack(context, field_list=('driver', 'xenv')):
return operator.attrgetter(*field_list)(context)
def example_step(context):
driver, xenv = unpack(context)
Run Code Online (Sandbox Code Playgroud)
如果你仍然不喜欢,那你就可以用globals().例如crate这样的函数:
def unpack(context, loc, field_list):
for field in field_list:
loc[field] = getattr(context, field, None)
Run Code Online (Sandbox Code Playgroud)
并在您的步骤中使用它:
def example_step(context):
unpack(context, globals(), ('driver', 'xenv'))
# now you can use driver and xenv local variables
driver.get('http://domain.com')
Run Code Online (Sandbox Code Playgroud)
这将减少代码中的重复,但它非常隐含并且可能很危险.因此不建议这样做.
我只是使用元组解包.它简单明了,因此不会导致其他错误.
| 归档时间: |
|
| 查看次数: |
4025 次 |
| 最近记录: |