AI自动写UI自动化用例


前言

有的同学看完我写的使用AI写自动化用例后,点了我一下:可以不可以使用AI自动生成UI自动化用例脚本?然后我就在想,这个想法太棒了,于是就有了这篇文章。

思路

  1. 由于之前使用AI生成测试用例后得出的经验,举一反三进行的还比较顺利,就不过多阐述ollama了
  2. 首先的话是获取网站的html,我看到了很多方法,比如使用requests库,但是感觉不太靠谱,然后我想起来了selenium,打开网站获html并保存到本地
url = '替换为需要抓取的网页地址'
driver = webdriver.Chrome()
driver.get(url)
html_content = driver.page_source
driver.quit()
  1. 在测试使用的过程中遇到了一个问题:AI自动写测试用例文章中的多个用户输入方法不行了,测试下来一直以最后一条内容为输出;然后我就想到了读取html后和提示词进行拼接发送给AI,然后就成功了😋
with open('webpage_dynamic.html', 'r', encoding='utf-8') as file:
    html_content = file.read()

prompt = ('你是一名专业的UI自动化测试工程师,根据我给出的网页的HTML使用python语言写出自动化测试脚本,'
          '你使用的技术为selenium,pytest,allure,正确的用户名为:admin,密码为:123456')

messages = [
    {
        'role': 'user',
        'content': str(html_content) + str(prompt)
    },
]
  1. 成功后然后就是使用python的正则进行匹配python代码,然后保存到本地的py文件中
def extract_python_code_from_output(output_text):
    """从AI返回内容中提取Python代码"""
    # 匹配Python代码块,包括import语句和后续的代码
    pattern = r'```python(.*?)```'
    matches = re.findall(pattern, output_text, re.DOTALL)
    
    if not matches:
        raise ValueError("没有匹配到Python代码")
    
    # 取第一个匹配的代码块,并去除前后空白
    python_code = matches[0].strip()
    return python_code
  1. 由于我写的代码太丑了,我把代码提交给了AI,然后AI给我加上了注释,我在修修改改,感觉好多了😋
  2. 由于我的电脑配置低部署的模型低是deepseek:7B,运行的效果很不好,需要用到更高的模型,代码中是:deepseek:70B(当然不是我的接口)

使用的技术工具
python Ollama vscode deepseek模型 chromedriver allure

加注释的完整代码

import re
from ollama import Client
import docx
import pandas as pd
import sys
from pathlib import Path
from selenium import webdriver

url = '替换为需要抓取的网页地址'
driver = webdriver.Chrome()
driver.get(url)
html_content = driver.page_source
driver.quit()

def extract_python_code_from_output(output_text):
    """从AI返回内容中提取Python代码"""
    # 匹配Python代码块,包括import语句和后续的代码
    pattern = r'```python(.*?)```'
    matches = re.findall(pattern, output_text, re.DOTALL)
    
    if not matches:
        raise ValueError("没有匹配到Python代码")
    
    # 取第一个匹配的代码块,并去除前后空白
    python_code = matches[0].strip()
    return python_code

def save_to_py_file(code, filename="保存为文件名字.py"):
    """将代码保存到.py文件"""
    try:
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(code)
        print(f"成功将测试脚本保存到 {filename}")
    except IOError as e:
        print(f"保存文件时出错: {e}")
        raise

def remove_think_tags(content):
    """移除 <think> 标签及其内容"""
    return re.sub(r'<think>.*?</think>', '', content, flags=re.DOTALL)

def generate_test_script():
    client = Client(
        host='你的ollama地址',
        headers={'x-some-header': 'some-value'}
    )

    with open('webpage_dynamic.html', 'r', encoding='utf-8') as file:
        html_content = file.read()
    
    prompt = ('你是一名专业的UI自动化测试工程师,根据我给出的网页的HTML使用python语言写出自动化测试脚本,'
              '你使用的技术为selenium,pytest,allure,正确的用户名为:admin,密码为:123456')
    
    messages = [
        {
            'role': 'user',
            'content': str(html_content) + str(prompt)
        },
    ]
    
    response = client.chat(model='deepseek-r1:70b', messages=messages)
    ai_content = response.message.content
    
    # 清理内容
    cleaned_content = remove_think_tags(ai_content)
    print("AI生成的原始内容:\n", cleaned_content)
    
    try:
        # 提取Python代码
        python_code = extract_python_code_from_output(cleaned_content)
        
        # 保存到文件
        save_to_py_file(python_code)
        print("测试脚本生成成功!")
        
    except ValueError as e:
        print(f"错误: {e}")
        print("未能从AI响应中提取出有效的Python代码")
        print("请检查AI返回的内容是否符合预期格式")
        sys.exit(1)
    except Exception as e:
        print(f"发生意外错误: {e}")
        sys.exit(1)

if __name__ == "__main__":
    generate_test_script()

其它

  1. 本地部署Ollama:https://www.sunweisu.xyz/2025/02/17/post/57724/
  2. 推荐使用本地部署的接口或者公司团体部署的AI接口,如果使用别人的接口可能会导致需求机密泄露
  3. 提示词根据自己的需要进行修改
  4. 优化的地方1:目前只实现了一个页面进行操作,需要实现多个页面,多个标签页进行操作
  5. 优化的地方2:页面中也会有一些动态元素和未加载的元素需要考虑

使用selenium+pytest+alluer输出结果报告(运行AI输出的代码)

  1. 安装pytest

    pip install pytest
  2. 安装allure-pytest

    pip install allure-pytest
  3. 代码中其它库报错,就下载对应的库

  4. 下载alluer
    下载地址:https://repo.maven.apache.org/maven2/io/qameta/allure/allure-commandline/
    下载解压,然后把bin目录添加到系统环境变量中的path,然后cmd输入allure –version,如果出现版本号则配置成功。

  5. 生成的html文件不能直接打开文件,需要使用命令行打开
    (1)首先pycharm执行使用pytest运行python文件

    pytest 你的文件名.py --alluredir ./allure-results

    (2)然后在pycharm执行把输出的测试结果进行生成测试报告

    allure generate ./allure-results -o ./allure-report --clean

    (3)在pycharm中右键选择浏览器打开
    pycharm

运行结果展示

部分结果展示


文章作者: 孙尾苏
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 孙尾苏 !
评论
  目录