【问题标题】:Parameter type definition in function of attribute Python属性Python函数中的参数类型定义
【发布时间】:2021-05-16 10:00:28
【问题描述】:

我是一名 TEA,我使用 Python + Selenium Webdriver 和 Behave 来运行我的测试。

为此,我在上下文中定义 webdriver 如下

    driver = webdriver.Chrome()
    driver.implicitly_wait(5)
    context.driver = driver
    context.driver.get('https://www.ebay.com/')

这是在一个函数中定义的,但我的问题是,当我想在另一个步骤函数中使用驱动程序时,我没有获得驱动程序功能的 sn-ps。这让我浪费了很多时间来寻找我正在尝试使用的函数的确切名称。

例如

@then('Click the "Search" button')
def step_impl(context: behave.runner.Context):
    """
    :type context: behave.runner.Context
    """
    search_btn = context.driver.find_element_by_xpath('//*[@id="gh-btn"]')
    search_btn.click()

我知道我可以定义直接接收的参数的类型

var_name: str (def step_impl(context: behave.runner.Context),但我正在寻找的案例更具体。比如 context.driver: 'webdriver object'

有没有办法定义 context.driver 类型,以便我的 ide 将解释这是一个 webdriver 对象并以这种方式获取驱动程序的方法?

我正在使用 PyCharm Professional

【问题讨论】:

  • 你试过什么?例如,您是否尝试过def step_impl(context: behave.runner.Context):?
  • 是的,但这只会让我访问 Context 对象函数,我正在定义一个名为 context.driver 的参数,它有一个 webdriver 对象
  • 我不知道表现如何,但如果输入正确,PyCharm 将能够从中找出context.driver 的类型。
  • context.driver的东西是我在另一个函数中定义的一个属性,不是behavior.runner.Context的内置属性

标签: python selenium pycharm gherkin python-behave


【解决方案1】:

PyCharm 应该可以使用这个:

@then('Click the "Search" button')
def step_impl(context: behave.runner.Context):
    """
    :type context: behave.runner.Context
    """
    driver: webdriver.Chrome = context.driver
    search_btn = driver.find_element_by_xpath('//*[@id="gh-btn"]')
    search_btn.click()

【讨论】:

  • 您能否详细说明您在类型声明行所做的工作? driver: webdriver.Chrome = context.driver 想了解这个语法。谢谢!
  • 称为变量类型注解,在PEP 526中有详细介绍和描述!它们用于dataclasses 等地方。
【解决方案2】:
def step_impl(context: WebDriver):
    search_btn = context.driver.find_element_by_xpath('//*[@id="gh-btn"]')
    search_btn.click()

您不必定义类型两次。

你需要的导入:

from selenium.webdriver.firefox.webdriver import WebDriver

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-24
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多