我在PyCharm中有一个示例项目 - 包含一个简单的测试,它检查登录到给定的正确Slack工作区 . 它有 web_drivers
目录,里面有 chromedriver
, conftest.py
有用于测试的webdriver和用于实际测试的 tests.py
,f.e .
conftest.py
import os
import pytest
from selenium import webdriver
@pytest.fixture(scope='class')
def driver_get(request):
web_driver = webdriver.Chrome(executable_path=os.path.join("web_drivers","chromedriver.exe"))
yield web_driver
def fin():
web_driver.close()
request.addfinalizer(fin)
tests.py
import pytest
class TestSlackWorkspace(object):
@pytest.fixture(autouse=True)
def setup(self, driver_get):
self.driver = driver_get
self.driver.get("https://slack.com/signin")
self.input_field = self.driver.find_element_by_xpath(
"//input[@type='text' and @id='domain']")
self.continue_button = self.driver.find_element_by_xpath(
"//button[@id='submit_team_domain']")
def test_correct_workspace(self):
self.input_field.send_keys("test")
self.continue_button.click()
assert self.driver.find_element_by_xpath("//h1[@id='signin_header']"
).is_displayed(), "Login page should be displayed"
现在的问题是将测试划分为页面初始化部分 - def setup
,并将实际测试执行部分 def test_correct_workspace
划分为不同的类和文件(类似于页面对象模式)
因此 conftest.py
的基数应相同,并将 test.py
除以
page.py
class SlackWorkspace(object):
@pytest.fixture(autouse=True)
def __init__(self, driver_get):
self.driver = driver_get
self.driver.get("https://slack.com/signin")
self.input_field = self.driver.find_element_by_xpath("//input[@type='text' and @id='domain']")
self.continue_button = self.driver.find_element_by_xpath("//button[@id='submit_team_domain']")
test.py
class TestWorkspace(object):
def test_correct_workspace(self):
self.input_field.send_keys("test")
self.continue_button.click()
login_page = self.driver.find_element_by_xpath("//h1[@id='signin_header']")
assert login_page.is_displayed(), "Login page should be displayed"
但肯定它不会以这种形式起作用:
1)不知何故 driver_get
应该导入页面初始化文件和转发器到 __init__
- ?
2)以某种方式页面初始化应该与其他文件中的测试实现相关联 - ?
不知道如何在单独的文件之间组织所有这些导入
2 回答
在Page Object模式中,应避免在测试类中直接引用驱动程序 . 您可以将page.py作为基类来使用常用方法 . 设置可以移动到不同的页面,例如login.py . 此设置方法应返回您要验证的页面 . 然后,测试方法应使用这些页面对象进行验证 . 我一直在conftest.py中登录,然后在测试和其他灯具中使用它 . 例如,这是我试图给你一个概述 . 你应该在page object pattern上阅读更多内容 .
我建议使用pytest-selenium插件,通过使用selenium和pytest减少大量的样板代码
在pytest -> How to use fixture return value in test method under a class的帮助下管理以找到解决方案,并通过以下方式从更多的经验者那里得到一些解释
1)原来,conftest中的fixture需要从
pages.py
传递我的登录页面的初始化webdriver,并使用内置的request
fixture用这个驱动程序初始化这个页面类 . 所以正确conftest.py
将如下所示:2)'pages.py'包括
SigninPage
的init和收到的webdriver,输入字段进入工作区,按钮继续,方法enter_workspace
实际上这样做并返回LogInPage
与login_page
字段进行检查,所以它看起来像:3)最后,
test.py
由两件事组成 - 通过从SigninPage
调用方法enter_workspace
进入工作区,打开LogInPage
,然后检查登录是否实际显示:它仍然需要改进,但问问题解决了 . 谢谢 .