使用pytest+selenium+allure实现web页面自动化测试

2023-12-21 10:57:47

测试文件

  • base 基本方法
  • data 测试数据
  • page web页面相关操作
  • image 测试截图
  • log 日志文件
  • report 测试报告文件
  • temp 临时文件
  • tool 文件读取,发邮件文件
  • TestCases 测试用例

在page下的__init__.py文件下配置

import os
import time
from selenium.webdriver.common.by import By

# 项目路径
PROJECT_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 图片路径
IMAGE_PATH = os.path.join(PROJECT_PATH, 'image')
# 测试数据路径
DATA_PATH = os.path.join(PROJECT_PATH, 'data')
# 日志路径
LOG_PATH = os.path.join(PROJECT_PATH, 'log')
# 测试报告
REPORT_PATH = os.path.join(PROJECT_PATH, 'report', 'html')
# 临时文件
TEMP_PATH = os.path.join(PROJECT_PATH, 'temp')
# 请求url
url = "http://cal.apple886.com/"

"""  邮件信息  """
email_host = "smtp.qq.com"  # SMTP服务器
email_sender = '2022204437@qq.com'  # 发件人
email_license = 'jxyvidactsaiicja'  # 授权码
email_receivers = ['2022204437@qq.com']  # 收件人(可以群发)

""" 以下为测试数据配置文件 """
image_path = os.path.join(IMAGE_PATH, '%serror.png' % time.strftime("%Y%m%d%H%M%S"))

"""  以下为测试数据配置文件   """
add_data = os.path.join(DATA_PATH, 'add.json')
multi_data = os.path.join(DATA_PATH, 'multi.json')
subtr_data = os.path.join(DATA_PATH, 'subtr.json')

"""  以下为logger配置文件   """
log_filename = os.path.join(LOG_PATH, '%sdemo.log' % time.strftime("%Y%m%d%H%M%S"))
log_when = "midnight"
log_interval = 1
log_backupCount = 30
log_encoding = "utf-8"
log_filemode = "w"
log_format = "%(asctime)s -[%(name)s]- %(levelname)s---[%(filename)s [%(funcName)s:%(lineno)s]] - %(message)s"
log_datefmt = "%Y-%m-%d %H:%M:%S"

""""   以下为计算机配置数据   """
computer_add = By.XPATH, '//*[@id="simpleAdd"]'
computer_subtr = By.XPATH, '//*[@id="simpleSubtr"]'
computer_multi = By.XPATH, '//*[@id="simpleMulti"]'
computer_divi = By.XPATH, '//*[@id="simpleDivi"]'
computer_clear = By.XPATH, '//*[@id="simpleClearAllBtn"]'
computer_equal = By.XPATH, '//*[@id="simpleEqual"]'
computer_value = By.XPATH, '//*[@id="resultIpt"]'

在base下创建一个webpage.py文件

from selenium.webdriver.support.wait import WebDriverWait
from web.counter.base.logger import GetLogger
from web.counter import page

log = GetLogger().get_logger()


class WebPage:

    def __init__(self, driver):
        log.info("初始化driver{}".format(driver))
        self.driver = driver

    # 查找元素
    def base_find_element(self, loc, timeout=30, poll_frequency=0.5):
        log.info("正在查找元素{}".format(loc))
        return WebDriverWait(
            self.driver, timeout=timeout, poll_frequency=poll_frequency).until(
            lambda x: x.find_element(*loc))

    # 点击
    def base_click(self, loc):
        log.info("点击元素{}".format(loc))
        self.base_find_element(loc).click()

    # 输入
    def base_input(self, loc, key):
        log.info("输入元素{}输入值为{}".format(loc,key))
        self.base_find_element(loc).clear()
        self.base_find_element(loc).send_keys(key)

    # 获取文本
    def base_get_test(self, loc):
        log.info("获取文本{}".format(loc))
        return self.base_find_element(loc).text

    # 获取属性值
    def base_get_value(self, loc):
        log.info("获取{}属性值".format(loc))
        return self.base_find_element(loc).get_attribute('value')

    # 截图
    def base_get_image(self):
        log.error("错误!!!错误!!!错误!!!")
        self.driver.get_screenshot_as_file(page.image_path)

在base下创建一个driver.py文件

from selenium import webdriver
from web.counter import page


class GetDriver:
    driver = None

    @classmethod
    def get_driver(cls):
        if cls.driver is None:
            cls.driver = webdriver.Edge()
            cls.driver.maximize_window()
            cls.driver.get(page.url)
        return cls.driver

    @classmethod
    def quit_driver(cls):
        if cls.driver:
            cls.driver.quit()
            cls.driver = None

在base下创建一个logger.py文件

import logging.handlers
from web.counter import page


class GetLogger:
    logger = None

    @classmethod
    def get_logger(cls):
        if cls.logger is None:
            # 获取日志器
            cls.logger = logging.getLogger()
            # 获取日志器级别
            cls.logger.setLevel(logging.INFO)
            # 获取处理器 控制台
            sh = logging.StreamHandler()
            # 获取处理器 文件-以以时间分隔
            th = logging.handlers.TimedRotatingFileHandler(
                filename=page.log_filename,
                when=page.log_when,
                interval=page.log_interval,
                backupCount=page.log_backupCount,
                encoding=page.log_encoding)
            fm = logging.Formatter(page.log_format)
            sh.setFormatter(fm)
            th.setFormatter(fm)
            cls.logger.addHandler(th)
            cls.logger.addHandler(sh)
        return cls.logger

在page下创建一个add_page.py文件

from selenium.webdriver.common.by import By

from web.counter.base.webpage import WebPage
from web.counter import page


class AddPage(WebPage):
    # 点击数字
    def page_click_num(self, num):
        for n in str(num):
            loc = By.XPATH, '//*[@id="simple{}"]'.format(n)
            self.base_click(loc)

    # 点击加号
    def page_click_add(self):
        self.base_click(page.computer_add)

    # 点击等于
    def page_click_equal(self):
        self.base_click(page.computer_equal)

    # 获取结果
    def page_get_value(self):
        return self.base_get_value(page.computer_value)

    # 清屏
    def page_click_clear(self):
        self.base_click(page.computer_clear)

    # 截图
    def page_get_image(self):
        self.base_get_image()

    # 组装加法
    def page_add(self, a, b):
        self.page_click_num(a)
        self.page_click_add()
        self.page_click_num(b)
        self.page_click_equal()


在TestCases 下创建一个test_add.py文件

from time import sleep
import pytest
from web.counter.page.add_page import AddPage
from web.counter.base.driver import GetDriver
from web.counter.tool.read_json import GetJson
from web.counter.base.logger import GetLogger
from web.counter import page

log = GetLogger().logger


class TestAdd:

    def setup_class(self):
        self.computer = AddPage(GetDriver().get_driver())

    def teardown_class(self):
        GetDriver().quit_driver()

    @pytest.mark.parametrize("a, b, result", GetJson().get_data(page.add_data))
    def test_add_computer(self, a, b, result):
        self.computer.page_click_clear()
        self.computer.page_add(a, b)
        try:
            assert self.computer.page_get_value() == str(result)
        except:
            log.error("错误")
            sleep(1)
            self.computer.page_get_image()
            raise

在tool下创建一个read_json.py文件

import json


class GetJson:
    data_lists = None
    data_dic = None

    # 读取json文件
    @classmethod
    def read_json(cls, json_path):
        with open(json_path, "r", encoding="utf-8") as f:
            return json.load(f)

    # 获取测试数据
    @classmethod
    def get_data(cls, json_path):
        cls.data_dic = cls.read_json(json_path)
        cls.data_lists = list()
        for data in cls.data_dic.values():
            cls.data_lists.append((data.get("a"), data.get("b"), data.get("result")))
        return cls.data_lists

在tool下创建一个send_emails.py文件

import time
import zipfile
import os
from email.mime.application import MIMEApplication
from web.counter import page
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart


class SendEmails:
    def __init__(self):
        self.mime = MIMEMultipart()
        self.allure_report = None
        self.report_path = page.REPORT_PATH
        self.temp_path = page.TEMP_PATH

    def send_email(self):
        self.mime['Subject'] = '%sxxx测试报告' % time.strftime('%Y年%m月%d日 %H:%M:%S ')
        content = 'hello, this is email content.'
        textApart = MIMEText(content)
        zip_Apart = MIMEApplication(open(SendEmails().make_zip, 'rb').read())
        zip_Apart.add_header('Content-Disposition', 'attachment', filename='allure_report.zip')

        self.mime.attach(textApart)
        self.mime.attach(zip_Apart)
        try:
            server = smtplib.SMTP(page.email_host)
            server.login(page.email_sender, page.email_license)
            server.sendmail(page.email_sender, page.email_receivers, self.mime.as_string())
            print('发送成功')
            server.quit()
        except smtplib.SMTPException as e:
            print('error:', e)  # 打印错误

    # 打包目录为zip文件(实际未压缩)
    @property
    def make_zip(self):
        if not os.path.exists(self.temp_path):
            os.makedirs(self.temp_path)
        self.allure_report = os.path.join(self.temp_path, 'allure_report.zip')
        zip_file = zipfile.ZipFile(self.allure_report, 'w')
        for present, dirs, files in os.walk(self.report_path):
            """
                present:现在的目录
                dirs:该目录下包含的子目录
                files:该目录下包含的文件
            """
            for file in files:
                pathfile = os.path.join(present, file)
                relpath = os.path.relpath(pathfile, page.PROJECT_PATH)  # 相对路径
                # ZIP_STORED:实际上并未压缩。
                zip_file.write(pathfile, relpath, zipfile.ZIP_STORED)
        zip_file.close()
        return self.allure_report


if __name__ == '__main__':
    report = page.REPORT_PATH
    temp = page.TEMP_PATH
    print(report)
    print(temp)
    SendEmails().send_email()
    print(SendEmails().allure_report)
    print("压缩包创建完成")

# import zmail
# from web.counter import page
#
#
# def send_report():
#     """发送报告"""
#
#     with open(page.REPORT_PATH, encoding='utf-8') as f:
#         content_html = f.read()
#     try:
#         mail = {
#             'from': '2022204437@qq.com',
#             'subject': '最新的测试报告邮件',
#             'content_html': content_html,
#             'attachments': [page.REPORT_PATH, ]
#         }
#         server = zmail.server(*page.EMAIL_INFO.values())
#         server.send_mail(page.ADDRESSEE, mail)
#         print("测试邮件发送成功!")
#     except Exception as e:
#         print("Error: 无法发送邮件,{}!", format(e))
#
#
# if __name__ == "__main__":
#     '''请先在config/conf.py文件设置QQ邮箱的账号和密码'''
#     send_report()

web自动化大体就是这样,然后测试数据可以自己写

文章来源:https://blog.csdn.net/qq_43592064/article/details/135123303
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。