我有一段时间搞清楚这一点,这真的让我烦恼,所以我想我会发布这个以防万一有人遇到同样的问题......
(答案是如此简单,它会伤害:-)
问题
问题的核心是,有时候,并非总是如此,当在PyTest中处理返回对象的灯具时,当你在PyCharm的测试中使用这些灯具时,你不会得到自动完成的提示.如果您在编写测试时想要引用具有大量方法的对象,则会给测试编写过程带来很多开销和不便.
这是一个简单的例子来说明这个问题:
假设我有一个"event_manager"类,它位于:
location.game.events
Run Code Online (Sandbox Code Playgroud)
让我们进一步说,在我的conftest.py文件中(对于不熟悉的PyTest标准事物),我有一个返回该类实例的fixture:
from location.game.events import event_manager
...
@pytest.fixture(scope="module")
def event_mgr():
"""Creates a new instance of event generate for use in tests"""
return event_manager()
Run Code Online (Sandbox Code Playgroud)
我有时会遇到问题(但并不总是 - 我不能完全弄明白为什么)这样的类,其中自动完成在我使用灯具的测试代码中无法正常工作,例如
def test_tc10657(self, evt_mgr):
"""Generates a Regmod and expects filemod to be searchable on server"""
evt_mgr.(This does not offer autocomplete hints when you type ".")
Run Code Online (Sandbox Code Playgroud)
所以答案实际上很简单,一旦你在PyCharm中查看类型提示:http: //www.jetbrains.com/help/pycharm/2016.1/type-hinting-in-pycharm.html
以下是修复上述测试代码以便自动完成正常工作的方法:
from location.game.events import event_manager
...
def test_tc10657(self, evt_mgr: event_manager):
"""Generates a Regmod and expects filemod to be searchable on server"""
evt_mgr.(This DOES offer hints when you type "." Yay!)
Run Code Online (Sandbox Code Playgroud)
请注意我是如何显式键入fixture作为event_manager类型的输入参数.
小智 2
此外,如果您向函数添加文档字符串并指定参数的类型,您将获得这些参数的代码完成。
例如使用 pytest 和 Selenium:
# The remote webdriver seems to be the base class for the other webdrivers
from selenium.webdriver.remote.webdriver import WebDriver
def test_url(url, browser_driver):
"""
This method is used to see if IBM is in the URL title
:param WebDriver browser_driver: The browser's driver
:param str url: the URL to test
"""
browser_driver.get(url)
assert "IBM" in browser_driver.title
Run Code Online (Sandbox Code Playgroud)
这也是我的 conftest.py 文件
import pytest
from selenium import webdriver
# Method to handle the command line arguments for pytest
def pytest_addoption(parser):
parser.addoption("--driver", action="store", default="chrome", help="Type in browser type")
parser.addoption("--url", action="store", default='https://www.ibm.com', help="url")
@pytest.fixture(scope='module', autouse=True)
def browser_driver(request):
browser = request.config.getoption("--driver").lower()
# yield the driver to the specified browser
if browser == "chrome":
driver = webdriver.Chrome(executable_path='/path/to/chromedriver')
else:
raise Exception("No driver for browser " + browser)
yield driver
driver.quit()
@pytest.fixture(scope="module")
def url(request):
return request.config.getoption("--url")
Run Code Online (Sandbox Code Playgroud)
使用 Python 2.7 和 PyCharm 2017.1 进行测试。文档字符串格式为 reStructuredText,并且在设置中选中了“分析文档字符串中的 Python 代码”复选框。