Allure2 报告中添加附件(日志)应用场景
- 应用场景:报告中添加详细的日志信息,有助于分析定位问题。
- 解决方案:
- Python:使用 python 自带的 logging 模块生成日志,日志会自动添加到测试报告中。
- Java:直接通过注解或调用方法添加。
Allure2 报告中添加日志 - Python
- 日志配置,在测试报告中使用
logger
对象生成对应级别的日志。
# 创建一个日志模块: log_util.py
import logging
import os
from logging.handlers import RotatingFileHandler
# 绑定绑定句柄到logger对象
logger = logging.getLogger(__name__)
# 获取当前工具文件所在的路径
root_path = os.path.dirname(os.path.abspath(__file__))
# 拼接当前要输出日志的路径
log_dir_path = os.sep.join([root_path, f'/logs'])
if not os.path.isdir(log_dir_path):
os.mkdir(log_dir_path)
# 创建日志记录器,指明日志保存路径,每个日志的大小,保存日志的上限
file_log_handler = RotatingFileHandler(os.sep.join([log_dir_path, 'log.log']), maxBytes=1024 * 1024, backupCount=10 , encoding="utf-8")
# 设置日志的格式
date_string = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(
'[%(asctime)s] [%(levelname)s] [%(filename)s]/[line: %(lineno)d]/[%(funcName)s] %(message)s ', date_string)
# 日志输出到控制台的句柄
stream_handler = logging.StreamHandler()
# 将日志记录器指定日志的格式
file_log_handler.setFormatter(formatter)
stream_handler.setFormatter(formatter)
# 为全局的日志工具对象添加日志记录器
# 绑定绑定句柄到logger对象
logger.addHandler(stream_handler)
logger.addHandler(file_log_handler)
# 设置日志输出级别
logger.setLevel(level=logging.INFO)
Allure2 报告中添加日志 - Python
- 代码输出到用例详情页面。
- 运行用例:
pytest --alluredir ./results --clean-alluredir
(注意不要加-vs)。
@allure.feature("功能模块2")
class TestWithLogger:
@allure.story("子功能1")
@allure.title("用例1")
def test_case1(self):
logger.info("用例1的 info 级别的日志")
logger.debug("用例1的 debug 级别的日志")
logger.warning("用例1的 warning 级别的日志")
logger.error("用例1的 error 级别的日志")
logger.fatal("用例1的 fatal 级别的日志")
Allure2 报告中添加日志 - Python
- 日志展示在 Test body 标签下,标签下可展示多个子标签代表不同的日志输出渠道:
- log 子标签:展示日志信息。
- stdout 子标签:展示 print 信息。
- stderr 子标签:展示终端输出的信息。
Allure2 报告中添加日志展示功能禁用 - Python
- 禁用日志,可以使用命令行参数控制
--allure-no-capture
pytest --alluredir ./results --clean-alluredir --allure-no-capture
llure2 添加附件(日志)实现方法 - Java
Allure 支持两种方法: - 注解方式添加。 - String类型添加。 - byte类型添加。 - 调用方法添加。 - String类型添加。 - InputStream类型添加。
注解方式 - Java
- 日志文件为String类型。
@DisplayName("注解方法 - 文本添加验证")
@Test
public void testAllureWithTxtAttachment() {
//3.添加到注解中
attachTxtFile(文件读取为String);
}
@Attachment(value = "描述信息", type = "text/plain")
public static String attachTxtFile(String txtContent) {
return txtContent;
}
日志文件为byte类型。 ```java
public void exampleTest() {
byte contents = Files.readAllBytes(Paths.get(“a.txt”));
attachTextFile(byte的文件, “描述信息”);
}
@Attachment(value = “{attachmentName}”, type = “text/plain”)
public byte attachTextFile(byte contents, String attachmentName) {
return contents;
}
---
### 注解方式
* 注解方式且日志文件为byte[]类型。
public void exampleTest() {
byte contents = Files.readAllBytes(Paths.get(“a.txt”));
attachTextFile(byte的文件, “描述信息”);
}
@Attachment(value = “{attachmentName}”, type = “text/plain”)
public byte attachTextFile(byte contents, String attachmentName) {
return contents;
}
### 调用方法 - Java
* 日志文件为String类型。 `java Allure.addAttachment("描述信息", "text/plain", 文件读取为String,"txt");`
* 日志文件为InputStream流。 `java Allure.addAttachment( "描述信息","text/plain", Files.newInputStream(文件Path), "txt");`
### 实例
package com.junit5.allure2report_addattachment_l3.addlog;
import io.qameta.allure.Allure;
import io.qameta.allure.Attachment;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
@DisplayName(“allure2报告中添加附件-日志”)
public class TextTest {
/**
* 注解:String类型
*/
@Test
@DisplayName(“注解:String类型”)
public void testAddTextForStringWithAn() throws IOException {
File file = new File(“a.txt”);
// BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file),“UTF-8”));
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line=bufferedReader.readLine())!=null){
stringBuffer.append(new String(line.getBytes(),“GBK”));
stringBuffer.append(System.lineSeparator());
}
attachTextFileWithString(stringBuffer.toString(),“text文本”);
}
@Attachment(value = "{fileName}",type = "text/plain")
String attachTextFileWithString(String contents,String fileName){
System.out.println("fileName:"+fileName);
return contents;
}
@Test
@DisplayName("注解:byte类型")
public void testAddTextForByteWithAn() throws IOException {
byte[] contents = Files.readAllBytes(Paths.get("a.txt"));
attachTextFileWithByte(contents,"byte数组添加文本");
}
@Attachment(value = "{fileName}",type = "text/plain")
byte[] attachTextFileWithByte(byte[] contents,String fileName){
System.out.println("fileName:"+fileName);
return contents;
}
@Test
@DisplayName("调用方法:String类型")
public void testAddTextForStringWithMethod() throws IOException {
File file = new File("a.txt");
// BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file),“UTF-8”));
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line=bufferedReader.readLine())!=null){
stringBuffer.append(new String(line.getBytes(), “gbk”));
stringBuffer.append(System.lineSeparator());
}
Allure.addAttachment(“方法添加String文本”,
“text/plain”,
stringBuffer.toString(),
“txt”);
}
@Test
@DisplayName("调用方法:stream流")
public void testAddTextForStreamWithMethod() throws IOException {
Allure.addAttachment("stream流添加String文本",
"text/plain",
Files.newInputStream(Paths.get("a.txt")),
"txt");
}
}
![image|800x301](upload://5PSG5QfvM6Rh7pON3VDbNbQCz8n.png)
![image|800x277](upload://rpGd1yBUiNtfMmkZiNJy3IzKlDC.png)
![image|800x268](upload://lgrLYtACqQKD1ouulih7MWaI8Z9.png)
![image|800x324](upload://jfmBIcdrjp1HaVQMEvJZJ23EBO8.png)