UI automated testing framework: PO mode + data-driven [detailed version]

Table of contents

1. Introduction to PO design pattern

What is PO model?

Advantages of PO model

2. Introduction to engineering structure

engineering structure

Frame features

3. Project code examples

page package

action package

business_process 包

util package

conf package


1. Introduction to PO design pattern

What is PO model?

The PO (PageObject) design pattern encapsulates the positioning of all element objects and operations on element objects of a page into a Page class, and writes test cases in units of pages to achieve the separation of page objects and test cases.

The design idea of ​​PO mode is similar to that of object-oriented, which can make the test code more readable, maintainable and reusable.


PO mode can divide a page into three levels: object library layer, operation layer, and business layer.

  1. Object library layer: encapsulates the method of positioning elements.

  2. Operation layer: encapsulates operations on elements.

  3. Business layer: combines one or more operations to complete a business function.

A test case may require multiple steps to operate elements. Each step is individually encapsulated into a method. When the test case is executed, the encapsulated method is called to perform the operation.

Advantages of PO model

  • Through page layering, the test code is separated from the page elements and operation methods of the tested page to reduce code redundancy.

  • Page objects are separated from use cases, business code is separated from test code, and coupling is reduced.

  • Different levels belong to different purposes, reducing maintenance costs.

  • Code readability is enhanced and the overall process is clearer.

2. Introduction to engineering structure

engineering structure

The entire testing framework is divided into four layers. Through layering, the test code is easier to understand and more convenient to maintain.

The first layer is the "test tool layer":

  • Util package: used to implement tool class methods called during testing, such as reading configuration files, operating methods of page elements, operating Excel files, etc.
  • conf package: configuration files and global variables.
  • test_data directory: Excel data file, including test data input and test result output.
  • log directory: log output file.
  • screenshot_path directory: directory where abnormal screenshots are saved.

The second layer is the "service layer", which is equivalent to a business encapsulation of the test object. For interface testing, it is an implementation of remote methods; for page testing, it is an encapsulation of page elements or operations.

  • Page package: object library layer and operation layer, which encapsulates the element object positioning and operations of all pages into one class.

The third layer is the "test case logic layer". This layer mainly organizes various business objects encapsulated in the service layer into test logic for verification.

  • action package: the process of assembling a single use case.

  • business_process package: Execute a collection of test cases based on the business layer and test data files.

  • test_data directory: Excel data file, including test data input and test result output. 
    The fourth layer is the "test scenario layer", which organizes test cases into test scenarios to implement various levels of case management, smoke generation, regression and other test scenarios. 

  • main.py: The main entry point for running this PO framework.

Insert image description here
Insert image description here

Frame features

  1. Through the configuration file, the page element positioning method and the test code are separated.
  2. Using the PO mode, the page elements in the web page are encapsulated to facilitate test code calls, and also achieve the goal of maintaining global validity in one place.
  3. Define multiple sets of test data in the excel file. Each logged-in user corresponds to a sheet that stores contact data. The test framework can automatically call the test data to complete data-driven testing.
  4. The logging function during test execution is implemented, and the test script execution status can be analyzed through log files.
  5. In the excel data file, you can customize the test data by setting the content of the "Test Data Execution" column to y or n. After the test execution is completed, the test execution time and results will be displayed in the "Test Result Column" for convenience. Testers view.

3. Project code examples

page package

The object library layer and operation layer encapsulate the element object positioning and operations of all pages into one class.

login_page.py

from conf.global_var import *
from util.ini_parser import IniParser
from util.find_element_util import *


# 登录页面元素定位及操作
class LoginPage:

    def __init__(self, driver):
        self.driver = driver
        # 初始化跳转登录页面
        self.driver.get(LOGIN_URL)
        # 初始化指定ini配置文件及指定分组
        self.cf = IniParser(ELEMENT_FILE_PATH, "126mail_loginPage")

    # 获取frame元素对象
    def get_frame_obj(self):
        locate_method, locate_exp = self.cf.get_value("loginPage.frame").split(">")
        return find_element(self.driver, locate_method, locate_exp)

    # 切换frame
    def switch_frame(self):
        self.driver.switch_to.frame(self.get_frame_obj())

    # 获取用户名输入框元素对象
    def get_username_input_obj(self):
        locate_method, locate_exp = self.cf.get_value("loginPage.username").split(">")
        return find_element(self.driver, locate_method, locate_exp)

    # 清空用户名输入框操作
    def clear_username(self):
        self.get_username_input_obj().clear()

    # 输入用户名操作
    def input_username(self, value):
        self.get_username_input_obj().send_keys(value)

    # 获取密码输入框元素对象
    def get_pwd_input_obj(self):
        locate_method, locate_exp = self.cf.get_value("loginPage.password").split(">")
        return find_element(self.driver, locate_method, locate_exp)

    # 输入密码操作
    def input_pwd(self, value):
        self.get_pwd_input_obj().send_keys(value)

    # 获取登录按钮对象
    def get_login_buttion_obj(self):
        locate_method, locate_exp = self.cf.get_value("loginPage.loginbutton").split(">")
        return find_element(self.driver, locate_method, locate_exp)

    # 点击登录按钮操作
    def click_login_button(self):
        self.get_login_buttion_obj().click()

home_page.py

from conf.global_var import *
from util.ini_parser import IniParser
from util.find_element_util import *


# 登录后主页元素定位及操作
class HomePage:

    def __init__(self, driver):
        self.driver = driver
        # 初始化指定ini配置文件及指定分组
        self.cf = IniParser(ELEMENT_FILE_PATH, "126mail_homePage")

    # 获取“通讯录”按钮对象
    def get_contact_button_obj(self):
        locate_method, locate_exp = self.cf.get_value("homePage.addressLink").split(">")
        return find_element(self.driver, locate_method, locate_exp)

    # 点击“通讯录”按钮
    def click_contact_button(self):
        self.get_contact_button_obj().click()

contact_page.py

from conf.global_var import *
from util.ini_parser import IniParser
from util.find_element_util import *


# 通讯录页面元素定位及操作
class ContactPage:

    def __init__(self, driver):
        self.driver = driver
        # 初始化指定ini配置文件及指定分组
        self.cf = IniParser(ELEMENT_FILE_PATH, "126mail_contactPersonPage")

    # 获取新建联系人按钮对象
    def get_contact_create_button_obj(self):
        locate_method, locate_exp = self.cf.get_value("contactPersonPage.createButton").split(">")
        return find_element(self.driver, locate_method, locate_exp)

    # 点击新建联系人按钮
    def click_contact_creat_button(self):
        self.get_contact_create_button_obj().click()

    # 获取姓名输入框对象
    def get_name_input_obj(self):
        locate_method, locate_exp = self.cf.get_value("contactPersonPage.name").split(">")
        return find_element(self.driver, locate_method, locate_exp)

    # 输入姓名操作
    def input_name(self, value):
        self.get_name_input_obj().send_keys(value)

    # 获取邮箱输入框对象
    def get_email_input_obj(self):
        locate_method, locate_exp = self.cf.get_value("contactPersonPage.email").split(">")
        return find_element(self.driver, locate_method, locate_exp)

    # 输入邮箱操作
    def input_email(self, value):
        self.get_email_input_obj().send_keys(value)

    # 获取星标联系人单选框对象
    def get_star_button_obj(self):
        locate_method, locate_exp = self.cf.get_value("contactPersonPage.starContacts").split(">")
        return find_element(self.driver, locate_method, locate_exp)

    # 点击星标联系人操作
    def click_star_button(self):
        self.get_star_button_obj().click()

    # 获取手机输入框对象
    def get_phone_input_obj(self):
        locate_method, locate_exp = self.cf.get_value("contactPersonPage.phone").split(">")
        return find_element(self.driver, locate_method, locate_exp)

    # 输入邮箱操作
    def input_phone(self, value):
        self.get_phone_input_obj().send_keys(value)

    # 获取备注输入框对象
    def get_remark_input_obj(self):
        locate_method, locate_exp = self.cf.get_value("contactPersonPage.otherinfo").split(">")
        return find_element(self.driver, locate_method, locate_exp)

    # 输入邮箱操作
    def input_remark(self, value):
        self.get_remark_input_obj().send_keys(value)

    # 获取确定按钮对象
    def get_confirm_button_obj(self):
        locate_method, locate_exp = self.cf.get_value("contactPersonPage.confirmButton").split(">")
        return find_element(self.driver, locate_method, locate_exp)

    # 点击星标联系人操作
    def click_confirm_button(self):
        self.get_confirm_button_obj().click()

action package

The business layer combines one or more operations to complete a business function.

case_action.py

from selenium import webdriver
import traceback
import time
from page.contact_page import ContactPage
from page.home_page import HomePage
from page.login_page import LoginPage
from conf.global_var import *
from util.log_util import *


# 初始化浏览器
def init_browser(browser_name):
    if browser_name.lower() == "chrome":
        driver = webdriver.Chrome(CHROME_DRIVER)
    elif browser_name.lower() == "firefox":
        driver = webdriver.Firefox(FIREFOX_DRIVER)
    elif browser_name.lower() == "ie":
        driver = webdriver.Ie(IE_DRIVER)
    else:
        return "Error browser name!"
    return driver


def assert_word(driver, text):
    assert text in driver.page_source


# 登录流程封装
def login(driver, username, pwd, assert_text):
    login_page = LoginPage(driver)
    login_page.switch_frame()
    login_page.clear_username()
    login_page.input_username(username)
    login_page.input_pwd(pwd)
    login_page.click_login_button()
    time.sleep(1)
    assert_word(driver, assert_text)


# 添加联系人流程封装
def add_contact(driver, name, email, phone, is_star, remark, assert_text):
    home_page = HomePage(driver)
    home_page.click_contact_button()
    contact_page = ContactPage(driver)
    contact_page.click_contact_creat_button()
    contact_page.input_name(name)
    contact_page.input_email(email)
    contact_page.input_phone(phone)
    contact_page.input_remark(remark)
    if is_star == "是":
        contact_page.click_star_button()
    contact_page.click_confirm_button()
    time.sleep(2)
    assert_word(driver, assert_text)


def quit(driver):
    driver.quit()


if __name__ == "__main__":
    driver = init_browser("chrome")
    login(driver, "zhangjun252950418", "zhangjun123", "退出")
    add_contact(driver, "铁蛋", "[email protected]", "12222222222", "是", "这是备注", "铁蛋")
    # quit(driver)

business_process 包

Based on the business layer and test files, implement data-driven test execution scripts.

batch_login_process.py

from action.case_action import *
from util.excel_util import *
from conf.global_var import *
from util.datetime_util import *
from util.screenshot import take_screenshot


# 封装测试数据文件中用例的执行逻辑
# 测试数据文件中的每个登录账号
def batch_login(test_data_file, browser_name, account_sheet_name):
        excel = Excel(test_data_file)
        # 获取登录账号sheet页数据
        excel.change_sheet(account_sheet_name)
        account_all_data = excel.get_all_row_data()
        account_headline_data = account_all_data[0]
        for account_row_data in account_all_data[1:]:
            # 执行登录用例
            account_row_data[ACCOUNT_TEST_TIME_COL] = get_english_datetime()
            if account_row_data[ACCOUNT_IS_EXECUTE_COL].lower() == "n":
                continue
            # 初始化浏览器
            driver = init_browser(browser_name)
            try:
                # 默认以"退出"作为断言关键字
                login(driver, account_row_data[ACCOUNT_USERNAME_COL], account_row_data[ACCOUNT_PWD_COL], "退出")
                info("登录成功【用户名:{}, 密码:{}, 断言关键字:{}】".format(account_row_data[ACCOUNT_USERNAME_COL],
                                                            account_row_data[ACCOUNT_PWD_COL], "退出"))
                account_row_data[ACCOUNT_TEST_RESULT_COL] = "pass"
            except:
                error("登录失败【用户名:{}, 密码:{}, 断言关键字:{}】".format(account_row_data[ACCOUNT_USERNAME_COL],
                                                            account_row_data[ACCOUNT_PWD_COL], "退出"))
                account_row_data[ACCOUNT_TEST_RESULT_COL] = "fail"
                account_row_data[ACCOUNT_TEST_EXCEPTION_INFO_COL] = traceback.format_exc()
                account_row_data[ACCOUNT_SCREENSHOT_COL] = take_screenshot(driver)
            # 写入登录用例的测试结果
            excel.change_sheet("测试结果")
            excel.write_row_data(account_headline_data, "red")
            excel.write_row_data(account_row_data)
            excel.save()

            # 切换另一个账号时需先关闭浏览器,否则会自动登录
            driver.quit()


if __name__ == "__main__":
    batch_login(TEST_DATA_FILE_PATH, "chrome", "126账号")

batch_login_and_add_contact_process.py

from action.case_action import *
from util.excel_util import *
from conf.global_var import *
from util.datetime_util import *
from util.screenshot import take_screenshot


# 封装测试数据文件中用例的执行逻辑
# 测试数据文件中每个登录账号下,添加所有联系人数据
def batch_login_and_add_contact(test_data_file, browser_name, account_sheet_name):
        excel = Excel(test_data_file)
        # 获取登录账号sheet页数据
        excel.change_sheet(account_sheet_name)
        account_all_data = excel.get_all_row_data()
        account_headline_data = account_all_data[0]
        for account_row_data in account_all_data[1:]:
            # 执行登录用例
            account_row_data[ACCOUNT_TEST_TIME_COL] = get_english_datetime()
            if account_row_data[ACCOUNT_IS_EXECUTE_COL].lower() == "n":
                continue
            # 初始化浏览器
            driver = init_browser(browser_name)
            # 获取联系人数据sheet
            contact_data_sheet = account_row_data[ACCOUNT_DATA_SHEET_COL]
            try:
                # 默认以"退出"作为断言关键字
                login(driver, account_row_data[ACCOUNT_USERNAME_COL], account_row_data[ACCOUNT_PWD_COL], "退出")
                info("登录成功【用户名:{}, 密码:{}, 断言关键字:{}】".format(account_row_data[ACCOUNT_USERNAME_COL],
                                                            account_row_data[ACCOUNT_PWD_COL], "退出"))
                account_row_data[ACCOUNT_TEST_RESULT_COL] = "pass"
            except:
                error("登录失败【用户名:{}, 密码:{}, 断言关键字:{}】".format(account_row_data[ACCOUNT_USERNAME_COL],
                                                            account_row_data[ACCOUNT_PWD_COL], "退出"))
                account_row_data[ACCOUNT_TEST_RESULT_COL] = "fail"
                account_row_data[ACCOUNT_TEST_EXCEPTION_INFO_COL] = traceback.format_exc()
                account_row_data[ACCOUNT_SCREENSHOT_COL] = take_screenshot(driver)
            # 写入登录用例的测试结果
            excel.change_sheet("测试结果")
            excel.write_row_data(account_headline_data, "red")
            excel.write_row_data(account_row_data)
            excel.save()

            # 执行添加联系人用例
            excel.change_sheet(contact_data_sheet)
            contact_all_data = excel.get_all_row_data()
            contact_headline_data = contact_all_data[0]
            # 在测试结果中,一个账号下的联系人数据标题行仅写一次
            contact_headline_flag = True
            for contact_row_data in contact_all_data[1:]:
                if contact_row_data[CONTACT_IS_EXECUTE_COL].lower() == "n":
                    continue
                contact_row_data[CONTACT_TEST_TIME_COL] = get_english_datetime()
                try:
                    add_contact(driver, contact_row_data[CONTACT_NAME_COL], contact_row_data[CONTACT_EMAIL_COL],
                                contact_row_data[CONTACT_PHONE_COL], contact_row_data[CONTACT_IS_STAR_COL],
                                contact_row_data[CONTACT_REMARK_COL], contact_row_data[CONTACT_ASSERT_KEYWORD_COL])
                    info("添加联系人成功【姓名:{}, 邮箱:{}, 手机号:{}, 是否星标联系人:{}, "
                         "备注:{}, 断言关键字:{}】".format(contact_row_data[CONTACT_NAME_COL], contact_row_data[CONTACT_EMAIL_COL],
                                                   contact_row_data[CONTACT_PHONE_COL], contact_row_data[CONTACT_IS_STAR_COL],
                                                   contact_row_data[CONTACT_REMARK_COL], contact_row_data[CONTACT_ASSERT_KEYWORD_COL]))
                    contact_row_data[CONTACT_TEST_RESULT_COL] = "pass"
                except:
                    error("添加联系人失败【姓名:{}, 邮箱:{}, 手机号:{}, 是否星标联系人:{}, "
                         "备注:{}, 断言关键字:{}】".format(contact_row_data[CONTACT_NAME_COL], contact_row_data[CONTACT_EMAIL_COL],
                                                   contact_row_data[CONTACT_PHONE_COL], contact_row_data[CONTACT_IS_STAR_COL],
                                                   contact_row_data[CONTACT_REMARK_COL], contact_row_data[CONTACT_ASSERT_KEYWORD_COL]))
                    contact_row_data[CONTACT_TEST_RESULT_COL] = "fail"
                    contact_row_data[CONTACT_TEST_EXCEPTION_INFO_COL] = traceback.format_exc()
                    contact_row_data[CONTACT_SCREENSHOT_COL] = take_screenshot(driver)
                # 写入登录用例的测试结果
                excel.change_sheet("测试结果")
                if contact_headline_flag:
                    excel.write_row_data(contact_headline_data, "red")
                    contact_headline_flag = False
                excel.write_row_data(contact_row_data)
                excel.save()

            # 切换另一个账号时需先关闭浏览器,否则会自动登录
            driver.quit()


if __name__ == "__main__":
    batch_login_and_add_contact(TEST_DATA_FILE_PATH, "chrome", "126账号")

util package

Used to implement tool class methods called during the test process, such as reading configuration files, operating methods of page elements, operating Excel files, etc.

excel_util.py

(openpyxl version: 3.0.4)

from openpyxl import load_workbook
from openpyxl.styles import PatternFill, Font, Side, Border
import os


class Excel:

    def __init__(self, test_data_file_path):
        # 文件格式校验
        if not os.path.exists(test_data_file_path):
            print("Excel工具类初始化失败:【{}】文件不存在!".format(test_data_file_path))
            return
        if not test_data_file_path.endswith(".xlsx") or not test_data_file_path.endswith(".xlsx"):
            print("Excel工具类初始化失败:【{}】文件非excel文件类型!".format(test_data_file_path))
            return
        # 打开指定excel文件
        self.wb = load_workbook(test_data_file_path)
        # 初始化默认sheet
        self.ws = self.wb.active
        # 保存文件时使用的文件路径
        self.test_data_file_path = test_data_file_path
        # 初始化红、绿色,供样式使用
        self.color_dict = {"red": "FFFF3030", "green": "FF008B00"}

    # 查看所有sheet名称
    def get_sheets(self):
        return self.wb.sheetnames

    # 根据sheet名称切换sheet
    def change_sheet(self, sheet_name):
        if sheet_name not in self.get_sheets():
            print("sheet切换失败:【{}】指定sheet名称不存在!".format(sheet_name))
            return
        self.ws = self.wb.get_sheet_by_name(sheet_name)

    # 返回当前sheet的最大行号
    def max_row_num(self):
        return self.ws.max_row

    # 返回当前sheet的最大列号
    def max_col_num(self):
        return self.ws.max_column

    # 获取指定行数据(设定索引从0开始)
    def get_one_row_data(self, row_no):
        if row_no < 0 or row_no > self.max_row_num()-1:
            print("输入的行号【{}】有误:需在0至最大行数之间!".format(row_no))
            return
        # API的索引从1开始
        return [cell.value for cell in self.ws[row_no+1]]

    # 获取指定列数据
    def get_one_col_data(self, col_no):
        if col_no < 0 or col_no > self.max_col_num()-1:
            print("输入的列号【{}】有误:需在0至最大列数之间!".format(col_no))
            return
        return [cell.value for cell in tuple(self.ws.columns)[col_no+1]]

    # 获取当前sheet的所有行数据
    def get_all_row_data(self):
        result = []
        # # API的索引从1开始
        for row_data in self.ws[1:self.max_row_num()]:
            result.append([cell.value if cell.value is not None else "" for cell in row_data])
        return result

    # 追加一行数据
    def write_row_data(self, data, fill_color=None, font_color=None, border=True):
        if not isinstance(data, (list, tuple)):
            print("追加的数据类型有误:需为列号或元组类型!【{}】".format(data))
            return
        self.ws.append(data)
        # 添加字体颜色
        if font_color:
            if font_color in self.color_dict.keys():
                font_color = self.color_dict[font_color]
            # 需要设置的单元格长度应与数据长度一致,否则默认与之前行的长度一致
        count = 0
        for cell in self.ws[self.max_row_num()]:
            if count > len(data) - 1:
                break
            # cell不为None,才能设置样式
            if cell:
                if cell.value in ["pass", "成功"]:
                    cell.font = Font(color=self.color_dict["green"])
                elif cell.value in ["fail", "失败"]:
                    cell.font = Font(color=self.color_dict["red"])
                else:
                    cell.font = Font(color=font_color)
            count += 1
        # 添加背景颜色
        if fill_color:
            if fill_color in self.color_dict.keys():
                fill_color = self.color_dict[fill_color]
            count = 0
            for cell in self.ws[self.max_row_num()]:
                if count > len(data) - 1:
                    break
                if cell:
                    cell.fill = PatternFill(fill_type="solid", fgColor=fill_color)
                count += 1
        # 添加单元格边框
        if border:
            bd = Side(style="thin", color="000000")
            count = 0
            for cell in self.ws[self.max_row_num()]:
                if count > len(data) - 1:
                    break
                if cell:
                    cell.border = Border(left=bd, right=bd, top=bd, bottom=bd)
                count += 1

    # 保存文件
    def save(self):
        self.wb.save(self.test_data_file_path)


if __name__ == "__main__":
    from conf.global_var import *
    excel = Excel(TEST_DATA_FILE_PATH)
    excel.change_sheet("登录1")
    # print(excel.get_all_row_data())
    excel.write_row_data((1,2,"嘻哈",None,"ddd"), "red", "green")
    excel.save()

find_element_util.py

from selenium.webdriver.support.ui import WebDriverWait


# 显式等待一个对象
def find_element(driver, locate_method, locate_exp):
    # 显式等待对象(最多等10秒,每0.2秒判断一次等待的条件)
    return WebDriverWait(driver, 10, 0.2).until(lambda x: x.find_element(locate_method, locate_exp))


# 显式等待一组对象
def find_elements(driver, locate_method, locate_exp):
    # 显式等待对象(最多等10秒,每0.2秒判断一次等待的条件)
    return WebDriverWait(driver, 10, 0.2).until(lambda x: x.find_elements(locate_method, locate_exp))

ini_parser.py

import configparser


class IniParser:

    # 初始化打开指定ini文件并指定编码
    def __init__(self, file_path, section):
        self.cf = configparser.ConfigParser()
        self.cf.read(file_path, encoding="utf-8")
        self.section = section

    # 获取所有分组名称
    def get_sections(self):
        return self.cf.sections()

    # 获取指定分组的所有键
    def get_options(self):
        return self.cf.options(self.section)

    # 获取指定分组的键值对
    def get_items(self):
        return self.cf.items(self.section)

    # 获取指定分组的指定键的值
    def get_value(self, key):
        return self.cf.get(self.section, key)

datetime_util.py

import time


# 返回中文格式的日期:xxxx年xx月xx日
def get_chinese_date():
    year = time.localtime().tm_year
    if len(str(year)) == 1:
        year = "0" + str(year)
    month = time.localtime().tm_mon
    if len(str(month)) == 1:
        month = "0" + str(month)
    day = time.localtime().tm_mday
    if len(str(day)) == 1:
        day = "0" + str(day)
    return "{}年{}月{}日".format(year, month, day)


# 返回英文格式的日期:xxxx/xx/xx
def get_english_date():
    year = time.localtime().tm_year
    if len(str(year)) == 1:
        year = "0" + str(year)
    month = time.localtime().tm_mon
    if len(str(month)) == 1:
        month = "0" + str(month)
    day = time.localtime().tm_mday
    if len(str(day)) == 1:
        day = "0" + str(day)
    return "{}/{}/{}".format(year, month, day)


# 返回中文格式的时间:xx时xx分xx秒
def get_chinese_time():
    hour = time.localtime().tm_hour
    if len(str(hour)) == 1:
        hour = "0" + str(hour)
    minute = time.localtime().tm_min
    if len(str(minute)) == 1:
        minute = "0" + str(minute)
    second = time.localtime().tm_sec
    if len(str(second)) == 1:
        second = "0" + str(second)
    return "{}时{}分{}秒".format(hour, minute, second)


# 返回英文格式的时间:xx:xx:xx
def get_english_time():
    hour = time.localtime().tm_hour
    if len(str(hour)) == 1:
        hour = "0" + str(hour)
    minute = time.localtime().tm_min
    if len(str(minute)) == 1:
        minute = "0" + str(minute)
    second = time.localtime().tm_sec
    if len(str(second)) == 1:
        second = "0" + str(second)
    return "{}:{}:{}".format(hour, minute, second)


# 返回中文格式的日期时间
def get_chinese_datetime():
    return get_chinese_date() + " " + get_chinese_time()


# 返回英文格式的日期时间
def get_english_datetime():
    return get_english_date() + " " + get_english_time()


if __name__ == "__main__":
    print(get_chinese_datetime())
    print(get_english_datetime())

log_util.py

import logging
import logging.config
from conf.global_var import *


# 日志配置文件:多个logger,每个logger指定不同的handler
# handler:设定了日志输出行的格式
#          以及设定写日志到文件(是否回滚)?还是到屏幕
#          还定了打印日志的级别
logging.config.fileConfig(LOG_CONF_FILE_PATH)
logger = logging.getLogger("example01")


def debug(message):
    logging.debug(message)


def info(message):
    logging.info(message)


def warning(message):
    logging.warning(message)


def error(message):
    logging.error(message)


if __name__ == "__main__":
    debug("hi")
    info("gloryroad")
    warning("hello")
    error("这是一个error日志")

screenshot.py

import traceback
import os
from util.datetime_util import *
from conf.global_var import *


# 截图函数
def take_screenshot(driver):
    # 创建当前日期目录
    dir = os.path.join(SCREENSHOT_PATH, get_chinese_date())
    if not os.path.exists(dir):
        os.makedirs(dir)
    # 以当前时间为文件名
    file_name = get_chinese_time()
    file_path = os.path.join(dir, file_name+".png")
    try:
        driver.get_screenshot_as_file(file_path)
        # 返回截图文件的绝对路径
        return file_path
    except:
        print("截图发生异常【{}】".format(file_path))
        traceback.print_exc()
        return file_path

conf package

Configuration files and global variables.

elements_repository.ini

[126mail_loginPage]
loginPage.frame=xpath>//iframe[contains(@id,'x-URS-iframe')]
loginPage.username=xpath>//input[@name='email']
loginPage.password=xpath>//input[@name='password']
loginPage.loginbutton=id>dologin

[126mail_homePage]
homePage.addressLink=xpath>//div[text()='通讯录']

[126mail_contactPersonPage]
contactPersonPage.createButton=xpath>//span[text()='新建联系人']
contactPersonPage.name=xpath>//a[@title='编辑详细姓名']/preceding-sibling::div/input
contactPersonPage.email=xpath>//*[@id='iaddress_MAIL_wrap']//input
contactPersonPage.starContacts=xpath>//span[text()='设为星标联系人']/preceding-sibling::span/b
contactPersonPage.phone=xpath>//*[@id='iaddress_TEL_wrap']//dd//input
contactPersonPage.otherinfo=xpath>//textarea
contactPersonPage.confirmButton=xpath>//span[.='确 定']

global_var.py

import os


# 工程根路径
PROJECT_ROOT_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# 元素定位方法的ini配置文件路径
ELEMENT_FILE_PATH = os.path.join(PROJECT_ROOT_PATH, "conf", "elements_repository.ini")

# 驱动路径
CHROME_DRIVER = "E:\\auto_test_driver\\chromedriver.exe"
IE_DRIVER = "E:\\auto_test_driver\\IEDriverServer.exe"
FIREFOX_DRIVER = "E:\\auto_test_driver\\geckodriver.exe"

# 测试使用的浏览器
BROWSER_NAME = "chrome"

# 登录主页
LOGIN_URL = "https://mail.126.com"

# 日志配置文件路径
LOG_CONF_FILE_PATH = os.path.join(PROJECT_ROOT_PATH, "conf", "logger.conf")

# 测试用例文件路径
TEST_DATA_FILE_PATH = os.path.join(PROJECT_ROOT_PATH, "test_data", "测试用例.xlsx")

# 截图保存路径
SCREENSHOT_PATH = os.path.join(PROJECT_ROOT_PATH, "screenshot_path")

# 单元测试报告输出目录
UNITTEST_REPORT_PATH = os.path.join(PROJECT_ROOT_PATH, "report")

# 登录账号sheet页数据列号
ACCOUNT_USERNAME_COL = 1
ACCOUNT_PWD_COL = 2
ACCOUNT_DATA_SHEET_COL = 3
ACCOUNT_IS_EXECUTE_COL = 4
ACCOUNT_TEST_TIME_COL = 5
ACCOUNT_TEST_RESULT_COL = 6
ACCOUNT_TEST_EXCEPTION_INFO_COL = 7
ACCOUNT_SCREENSHOT_COL = 8

# 联系人sheet页数据列号
CONTACT_NAME_COL = 1
CONTACT_EMAIL_COL = 2
CONTACT_IS_STAR_COL = 3
CONTACT_PHONE_COL = 4
CONTACT_REMARK_COL = 5
CONTACT_ASSERT_KEYWORD_COL = 6
CONTACT_IS_EXECUTE_COL = 7
CONTACT_TEST_TIME_COL = 8
CONTACT_TEST_RESULT_COL = 9
CONTACT_TEST_EXCEPTION_INFO_COL = 10
CONTACT_SCREENSHOT_COL = 11


if __name__ == "__main__":
    print(PROJECT_ROOT_PATH)

logger.conf

###############################################
[loggers]
keys=root,example01,example02
[logger_root]
level=DEBUG
handlers=hand01,hand02

[logger_example01]
handlers=hand01,hand02
qualname=example01
propagate=0

[logger_example02]
handlers=hand01,hand03
qualname=example02
propagate=0

###############################################
[handlers]
keys=hand01,hand02,hand03

[handler_hand01]
class=StreamHandler
level=INFO
formatter=form01
args=(sys.stderr,)

[handler_hand02]
class=FileHandler
level=DEBUG
formatter=form01
args=('.\\log\\126_mail_test.log', 'a')

[handler_hand03]
class=handlers.RotatingFileHandler
level=INFO
formatter=form01
args=('.\\log\\126_mail_test.log', 'a', 10*1024*1024, 5)

###############################################
[formatters]
keys=form01,form02

[formatter_form01]
format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
datefmt=%Y-%m-%d %H:%M:%S

[formatter_form02]
format=%(name)-12s: %(levelname)-8s %(message)s
datefmt=%Y-%m-%d %H:%M:%S

test_data directory

Test case.xlsx: contains test data input and test result output

Insert image description here
Insert image description here

log directory

Log output file: 126_mail_test.log

...
...
2021-02-23 16:59:15 log_util.py[line:19] INFO 登录成功【用户名:zhangjun252950418, 密码:zhangjun123, 断言关键字:退出】
2021-02-23 16:59:20 log_util.py[line:19] INFO 添加联系人成功【姓名:lily, 邮箱:[email protected], 手机号:135xxxxxxx1, 是否星标联系人:是, 备注:常联系人, 断言关键字:[email protected]
2021-02-23 16:59:24 log_util.py[line:27] ERROR 添加联系人失败【姓名:张三, 邮箱:[email protected], 手机号:158xxxxxxx3, 是否星标联系人:否, 备注:不常联系人, 断言关键字:[email protected]
2021-02-23 16:59:27 log_util.py[line:19] INFO 添加联系人成功【姓名:李四, 邮箱:[email protected], 手机号:157xxxxxx9, 是否星标联系人:否, 备注:, 断言关键字:李四】
...
...

screenshot_path directory

Abnormal screenshot saving directory:

Insert image description here

main.py

The main entrance to the operation of this PO framework.

from business_process.batch_login import *
from business_process.batch_login_and_add_contact import *
from conf.global_var import *


# 示例组装:冒烟测试
def smoke_test():
    batch_login(TEST_DATA_FILE_PATH, "chrome", "126账号")


# 示例组装:全量测试
def full_test():
    batch_login_and_add_contact(TEST_DATA_FILE_PATH, "chrome", "126账号")


if __name__ == "__main__":
    # smoke_test()
    full_test()

The following are relatively good learning tutorial resources that I have collected. Although they are not very valuable, if you happen to need them, you can leave a message in the comment area [777] and just take them away.

Friends who want to get information, please like + comment + collect , three times in a row!

After three consecutive rounds , I will send you private messages one by one in the comment area~

Guess you like

Origin blog.csdn.net/m0_70618214/article/details/133043549