首页 > 解决方案 > 属性Python函数中的参数类型定义

问题描述

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

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

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

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

例如

@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 对象'

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

我正在使用 PyCharm Professional

标签: pythonseleniumpycharmgherkinpython-behave

解决方案


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()

推荐阅读