gpt4 book ai didi

python - 如何分离测试和 fixture

转载 作者:行者123 更新时间:2023-12-04 16:45:31 24 4
gpt4 key购买 nike

我在 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)页面初始化应该以某种方式与其他文件中的测试实现相关联-?

不知道如何在单独的文件之间组织所有这些导入

最佳答案

在页面对象模式中,应避免在测试类中直接引用驱动程序。您可以将 page.py 作为基类来拥有通用方法。设置可以移动到不同的页面,例如登录.py此设置方法应返回您尝试验证的页面。然后测试方法应该使用这些页面对象进行验证。我在 conftest.py 中作为 fixture 登录,然后在测试和其他 fixture 中使用它。例如,这是我试图为您提供概述的尝试。您应该在 page object pattern 上阅读更多信息.

我建议使用 pytest-selenium使用 selenium 和 pytest 减少大量样板代码的插件

conftest.py

@fixture
def selenium():
# pytest-selenium provides this fixture & you can override it if required.
return selenium

@fixture
def home(selenium):
#do login
return HomePage
login.py

from page import Page #Import base class with common methods.

class LoginPage(Page):

def login(self, driver):
#do the login steps
return HomePage #return Landing Page
test_login.py

def test_login_successful(home): #Use the home fixture
assert home.is_displayed("xyz")

关于python - 如何分离测试和 fixture ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53705219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com