02. Optimize UI automation test script for login function

In the last article, we completed the automatic Hu script of the login function. In order to improve the code reusability, we encapsulated and improved the repeated code.

Write Driver tool class

Create tool class: driver_utils class, used to create and manage WebDriver instances

  • get_driver()method is used to get webdriverthe instance, create a Chrome WebDriver instance if the instance does not exist, and maximize the window. This method uses the singleton pattern to ensure that only one WebDriver instance is used throughout the test, avoiding repeated creation and destruction of WebDriver instances.
  • The ** quit_driver()** method is used to close and destroy the WebDriver instance. This method will determine whether there is a WebDriver instance currently, and if it exists, close it and set the instance to None .
class DriverUtils:
    __driver = None
    @classmethod
    def get_driver(cls):
        """
        创建驱动
        :return:
        """
        # 先判断驱动是否存在,如果存在已经存在,直接返回,如果不存在,创建驱动
        if cls.__driver is None:
            cls.__driver=webdriver.Chrome()
            cls.__driver.maximize_window()
            # cls.__driver.implicitly_wait(20)#隐式等待20秒
        return cls.__driver

    @classmethod
    def quit_driver(cls):
        """
        关闭驱动
        :return:
        """
        # 先判断驱动是否关闭人,如果已关闭不想要处理,
        if cls.__driver:
            cls.__driver.quit()
            cls.__driver = None

Create a base page class: BasePage

base_page.py is a base page class used to encapsulate common page operations and methods so that other page classes can inherit and reuse these common operations.
main effect:

  1. Encapsulate page element positioning and operation methods
  2. Public methods for fetching pages
  3. Encapsulates the public assertion method of the page
  4. Handle the common logic and exceptions of the page

In general, the role of base_page.py is to provide a basic page class, encapsulate common page operations and methods, so that other page classes can inherit and reuse these common operations, and improve code reusability and maintainability . It is an important part of UI automation testing framework.

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class BasePage:
    def __init__(self,driver:webdriver.Chrome):
        self.driver=driver
    #定位元素方法
    def find_el(self,loc,timeout=15,poll=1):
        """
        封装查找元素的方法
        :param loc: 元素定位的方式,类型,元组,(By.xxx,value)
        :param timeout: 最大等待时间
        :param poll:间隔时间
        :return:返回元素对象
        """
        try:
            element = WebDriverWait(self.driver, timeout, poll).until(
                EC.visibility_of_element_located(loc)
            )
            return element
        except Exception as e:
            print(f"未找到元素定位的方式:{
      
      loc} 的元素")
            raise e

    def input(self, el, text):
        """
    封装输入的方法
        :param el: 元素对象
        :param text: 输入的内容
        :return:
        """
        el.clear()
        el.se

full code

page1_login.py

import time

from selenium.webdriver.common.by import By

from page.base_page import BasePage
from utils.driver_util import DriverUtils
class LoginPage(BasePage):
    def __init__(self):
        super().__init__(DriverUtils.get_driver())
        self.username_locator = (By.XPATH, '//input[@placeholder="用户名"]')
        # 密码输入框
        self.password = By.XPATH, '//input[@placeholder="密码"]'
        #验证码
        self.code = By.XPATH,'//input[@placeholder="验证码"]'
        # 登录按钮
        self.login_btn = By.XPATH, '//input[@value="登录"]'

    def manage_login(self, username, password):
        # 1. 用户名输入框
        username_input = self.find_el(self.username_locator)
        self.input(username_input, username)
        # 2. 密码输入框
        self.input(self.find_el(self.password),password)
        # 3. 验证码输入框
        self.input(self.find_el(self.code),'lemon')
        # 4. 登录按钮
        login_btn=self.find_el(self.login_btn)
        login_btn.click()
        self.driver.implicitly_wait(5)
        user = self.driver.find_element_by_xpath('//div[@class="el-dropdown"]/span[text()="student"]')
        #断言
        assert user.text == username
        print(user.text)

test1_manage_login.py

import pytest

from page.manage.page1_login import LoginPage
class TestManageLogin:
    @pytest.mark.usefixtures('setup_tear_down')
    def test_manage_login(self,setup_tear_down):
        cl=LoginPage()
        cl.manage_login(username='student',password='123456a')

conftest.py

import pytest

from utils.driver_util import DriverUtils


@pytest.fixture(scope='class')
def setup_tear_down():
    driver = DriverUtils.get_driver()
    driver.get('http://mall.lemonban.com/admin/#/login')
    yield
    DriverUtils.quit_driver()

Guess you like

Origin blog.csdn.net/AAIT11/article/details/130781957