AI自动写测试用例


介绍

最近查了网上的东西好像没有相关的东西,所以自己写了一个,主要功能是读取需求,然后丢给AI,AI生成测试用例,把输出的结果给结构化一下,然后写入excel文件中。

思路及实现过程

  1. 首先看Ollama的api和openai的文档,发现兼容openai的库,结果不太理想(如果是调用官方openAI或者其他反代等可以使用此方法,我使用的是本地部署的模型)
  2. 通过在搜索发现有Ollama的库通过接口直接调用本地的模型,比官方给的简单的多,链接:https://pypi.org/project/ollama/
  3. 在看Ollama库的时候没有上传文件的功能,只能把需求文档给读出来然后传给AI
    def read_word_file(file_path):
        doc = docx.Document(file_path)
        full_text = []
        for para in doc.paragraphs:
            full_text.append(para.text)
        return '\n'.join(full_text)
  4. 在实现的过程中发现,获取deepseek的输出中,把思考的过程也一并的输出了,然后做了一个把AI思考的过程给过滤掉了
    def remove_think_tags(content):
        return re.sub(r'<think>.*?</think>', '', content, flags=re.DOTALL)
  5. 又发现一个问题AI每次输出的结果都不一致(可能是我提示词的原因),所以做了正则表达式来匹配字段并结构化数据,这样就得到了可以写入excel的数据
    def extract_test_cases(content):
        test_case_pattern = re.compile(
            r"测试用例\s*:(.*?)\s*标题\s*:(.*?)\s*前置条件\s*:(.*?)\s*操作步骤\s*:(.*?)\s*预期结果\s*:(.*?)(?=\n\s*测试用例:|\Z)",
            re.DOTALL
        )
    
  6. 生成的用例是多个的,把所有的结果进行匹配后,把结果循环输出
    matches = test_case_pattern.findall(content)
    
    test_cases = []
    for match in matches:
        test_case = {
            "测试用例": match[0].strip(),
            "标题": match[1].strip(),
            "前置条件": match[2].strip(),
            "操作步骤": "\n".join([step.strip() for step in match[3].split("\n") if step.strip()]),
            "预期结果": "\n".join([result.strip() for result in match[4].split("\n") if result.strip()]),
        }
        test_cases.append(test_case)
    
    return test_cases
  7. 然后就是写入excel文件了,如果没有结构化数据那么就不会写入excel文档
    def save_to_excel(test_cases, file_path):
        df = pd.DataFrame(test_cases)
        
        with pd.ExcelWriter(file_path, engine='xlsxwriter') as writer:
            df.to_excel(writer, index=False, sheet_name='测试用例')
            
            worksheet = writer.sheets['测试用例']
            
            for idx, col in enumerate(df.columns):
                worksheet.set_column(idx, idx, 30)
                for row in range(len(df) + 1):
                    worksheet.write(row, idx, df.iloc[row - 1][col] if row > 0 else col, writer.book.add_format({'text_wrap': True}))
    
    excel_file_path = 'C:/Users/用户名/Desktop/其它/测试用例.xlsx'
    
    save_to_excel(extracted_test_cases, excel_file_path)
    
    print(f"测试用例已保存到文件: {excel_file_path}")

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

加注释的完整代码

需要下载的库:ollama docx pandas xlsxwriter
命令行执行pip install 库名

import re
from ollama import Client
import docx
import pandas as pd

# 初始化Ollama客户端
client = Client(
  host='你的ip地址',
  headers={'x-some-header': 'some-value'}
)

# 读取Word文件内容
def read_word_file(file_path):
    doc = docx.Document(file_path)
    full_text = []
    for para in doc.paragraphs:
        full_text.append(para.text)
    return '\n'.join(full_text)

# 文件路径
word_file_path = 'C:/Users/需求文档.docx'

# 读取文件内容
word_content = read_word_file(word_file_path)

# 将文件内容添加到messages中
messages = [
    {
        'role': 'user',
        'content': '根据需求,按符合需求的测试方法输出测试用例,测试用例模板必须只有:“测试用例:,标题:,前置条件:,操作步骤:,预期结果:”注意:要格式化输出,不要输出其它无关内容!',
    },
    {
        'role': 'user',
        'content': f"Word文件内容:\n{word_content}\n",
    }
]

# 发送请求并获取响应
response = client.chat(model='deepseek-r1:14b', messages=messages)

# 假设 AI 生成的内容如下
ai_content = response.message.content


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

# 定义正则表达式来匹配字段
def extract_test_cases(content):
    # 正则表达式匹配每个测试用例
    test_case_pattern = re.compile(
        r"测试用例\s*:(.*?)\s*标题\s*:(.*?)\s*前置条件\s*:(.*?)\s*操作步骤\s*:(.*?)\s*预期结果\s*:(.*?)(?=\n\s*测试用例:|\Z)",
        re.DOTALL
    )
    
    # 查找所有匹配的测试用例
    matches = test_case_pattern.findall(content)
    
    # 将匹配结果转换为结构化数据
    test_cases = []
    for match in matches:
        test_case = {
            "测试用例": match[0].strip(),
            "标题": match[1].strip(),
            "前置条件": match[2].strip(),
            "操作步骤": "\n".join([step.strip() for step in match[3].split("\n") if step.strip()]),
            "预期结果": "\n".join([result.strip() for result in match[4].split("\n") if result.strip()]),
        }
        test_cases.append(test_case)
    
    return test_cases

# 调用函数提取测试用例
extracted_test_cases = extract_test_cases(cleaned_content)
print(extracted_test_cases)
print("_______________________________________________________________")

# 打印提取的测试用例
if extracted_test_cases:
    for idx, test_case in enumerate(extracted_test_cases, start=1):
        print(f"测试用例 {idx}:")
        print(f"测试用例名称: {test_case['测试用例']}")
        print(f"标题: {test_case['标题']}")
        print(f"前置条件: {test_case['前置条件']}")
        print(f"操作步骤: {test_case['操作步骤']}")
        print(f"预期结果: {test_case['预期结果']}")
        print()
else:
    print("未提取到测试用例内容,请检查AI生成的内容格式。")

# 将提取的测试用例保存到 Excel 文件
def save_to_excel(test_cases, file_path):
    # 将测试用例转换为 DataFrame
    df = pd.DataFrame(test_cases)
    
    # 设置 Excel 写入器,支持自动换行
    with pd.ExcelWriter(file_path, engine='xlsxwriter') as writer:
        df.to_excel(writer, index=False, sheet_name='测试用例')
        
        # 获取工作表对象
        worksheet = writer.sheets['测试用例']
        
        # 设置列宽和自动换行
        for idx, col in enumerate(df.columns):
            # 设置列宽
            worksheet.set_column(idx, idx, 30)
            # 设置自动换行
            for row in range(len(df) + 1):
                worksheet.write(row, idx, df.iloc[row - 1][col] if row > 0 else col, writer.book.add_format({'text_wrap': True}))

# 定义 Excel 文件路径
excel_file_path = 'C:/Users/其它/测试用例.xlsx'

# 保存到 Excel 文件
save_to_excel(extracted_test_cases, excel_file_path)

print(f"测试用例已保存到文件: {excel_file_path}")

其它

  1. 本地部署Ollama:https://www.sunweisu.xyz/2025/02/17/post/57724/
  2. 推荐使用本地部署的接口或者公司团体部署的AI接口,如果使用别人的接口可能会导致需求机密泄露
  3. 如果想要添加其他的测试用例字段:修改AI提示词,在extract_test_cases中添加对应的字段
  4. 部署其他模型修改response = client.chat(model=’你的模型名字’, messages=messages)
  5. 修改API:
    client = Client(
      host='你的地址',
      headers={'x-some-header': 'some-value'}
    )
  6. 优化方向:AI提示词优化,把生成的excel命名为时间这样就不会生成错误了,修改正则匹配,其它的暂时没有想到,有空后续优化
  7. 因为每次AI的结果不是一样的,所以有时候会匹配不到结果就不会写入excel文档,或者都在一行写着,只需要重新运行即可
  8. 如果不够细腻或者想以特定的测试方法进行生成只需要修改AI提示词即可,保证AI输出包含你设置的测试用例字段

运行结果展示

输出结果
测试用例结果

模型运行要求

Windows仅供参考其它系统可以自行百度

DeepSeek R1模型: 1.5B (4-bit)
GPU 运行:
最低3GB显存(如GTX 1060 6GB)
CPU 运行:
需4核CPU + 8GB内存
模型大小: 1.1GB
ollama run deepseek-r1:1.5b

DeepSeek R1模型: 7B (4-bit)
GPU 运行:
最低4GB显存(如GTX 1650)
CPU 运行:
需8核CPU + 16GB内存
模型大小: 4.7GB
ollama run deepseek-r1:7b

DeepSeek R1模型: 8B (4-bit)
GPU 运行:
最低5GB显存(如GTX 1660)
CPU 运行:
需8核CPU + 18GB内存
模型大小: 4.9GB
ollama run deepseek-r1:8b

DeepSeek R1模型: 14B (4-bit)
GPU 运行:
最低8GB显存(如RTX 3070)
CPU 运行:
需12核CPU + 32GB内存
模型大小: 9.0GB
ollama run deepseek-r1:14b

DeepSeek R1模型: 32B (4-bit)
GPU 运行:
推荐24GB显存(如RTX 4090)
CPU 运行:
需16核CPU + 64GB内存
模型大小: 20GB
ollama run deepseek-r1:32b

DeepSeek R1模型: 70B (4-bit)
GPU 运行:
需多卡(如2xA100 40GB)
CPU 运行:
需32核CPU + 128GB内存
模型大小: 43GB
ollama run deepseek-r1:70b


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