python-3.x 如何使用selenium和pytest框架处理UI自动化中的问题,如“您必须关闭浏览器才能完成注销过程”

8gsdolmq  于 2023-07-01  发布在  Python
关注(0)|答案(1)|浏览(121)

观察结果:
我正在运行我的数据驱动的UI自动化使用 selenium 与pytest框架和有60个测试用例。
现在Scope处于会话级别,并且在设置模块中仅登录应用程序一次。
所以现在的场景是,测试用例开始执行:
1.会话级别的设置和拆除:
@pytest.fixture(scope=“session”)setup module():login_to_the_application()拆卸模块():kill_browser_instance()
1.测试用例开始:
@pytest.mark.ui def test_verify_table_data(setup_module,data):#data是在www.example.com文件中创建并设置为fixture的全局变量conftest.py。

db_records = fetching_records_for_data_from_db(data)
#db_records consist 200 rows of data and this we will validate from ui one by one row.

for record in db_records():
    value = validating_row_data_in_ui_table(record)
    if value is True:
       print(pass)
    else:
       print(fail)

因此,这个完整的流程只执行到4到5个数据,然后自动显示消息,如您必须关闭浏览器才能完成注销过程。
不知道该如何处理这种情况。任何帮助或线索都是好的先谢谢你。

pcww981p

pcww981p1#

下面是一个完整的脚本,可以用pytest运行,它定义了setUp()tearDown()方法,这样浏览器就可以在测试开始和结束时自动打开和关闭:(这是使用fixture的替代方案,因为pytest可以与unittest.TestCase结合使用,这可能有助于更好地构建内容,以确保在测试结束时关闭浏览器。

import sys
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from unittest import TestCase

class SeleniumClass(TestCase):
    def setUp(self):
        self.driver = None
        options = webdriver.ChromeOptions()
        options.add_argument("--disable-notifications")
        if "linux" in sys.platform:
            options.add_argument("--headless=new")
        options.add_experimental_option(
            "excludeSwitches", ["enable-automation", "enable-logging"],
        )
        prefs = {
            "credentials_enable_service": False,
            "profile.password_manager_enabled": False,
        }
        options.add_experimental_option("prefs", prefs)
        self.driver = webdriver.Chrome(options=options)

    def tearDown(self):
        if self.driver:
            try:
                if self.driver.service.process:
                    self.driver.quit()
            except Exception:
                pass

    def test_login(self):
        self.driver.get("https://www.saucedemo.com")
        by_css = By.CSS_SELECTOR  # "css selector"
        element = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable((by_css, "#user-name"))
        )
        element.send_keys("standard_user")
        element = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable((by_css, "#password"))
        )
        element.send_keys("secret_sauce")
        element.submit()
        WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((by_css, "div.inventory_list"))
        )
        time.sleep(1)

# When run with "python" instead of "pytest" or "python -m unittest"
if __name__ == "__main__":
    from unittest import main
    main()

相关问题