干货 | REST-assured 获取日志到文件并结合 Allure 报告进行展示

94 阅读4分钟

使用 Rest-assured 集合 Allure 运行完用例之后,在生成的报告中只有断言信息,没有请求的日志信息。而当我们的用例失败时,特别是接口失败时,请求日志是分析原因的第一手资源。那如何将 Rest-assured 产生的日志存入 Allure 里,并且能和用例一一对应起来呢?

在使用 Rest-assured 集合 Allure 运行完用例之后,查看生成的报告信息如下:

我们可以看到在生成的报告中只有断言信息,而没有请求的日志信息,而当我们的用例失败时,特别是接口失败时,请求日志是分析原因的第一手资源;

其实Rest-assured是有请求日志的,可以通过在given()和then()后面加上.log().all()来打印全部的日志信息: 那么问题来了,如何将这打印出来的日志信息都"转移"到 Allure 报告中呢?并且能和用例一一对应起来,然后就开始了探索之路~

首先来看一下 Allure 报告可以如何展示日志,在学习 Allure 的过程中发现 Allure有添加附件展示的功能,那么我就直接想到将日志能存入文件然后添加到报告附件不就可以了吗?由此,Allure 端的解决方向确定。 接下来就是要想法办将 Rest-assured 产生的日志存入文件了; 整体思路: 【Rest-assured打印日志】- 【Rest-assured日志存入文件】- 【文件以附件形式传入Allure】- 【Allure展示附件日志】

先看一下Allure 添加附件的两种方法: @Attachment:在方法上添加注解@Attachment,方法的返回值就会作为附件上传,可添加展示文本和附件类型

@Attachment(value = "Page screenshot", type = "image/png")

Allure.addAttachment:通过addAttachment方法指定要添加的附件和展示信息

public static void addHttpLogToAllure() {
        try {
                    Allure.addAttachment("接口请求响应日志",
                                        new FileInputStream("src/main/resources/test.log"));
                                                } catch (FileNotFoundException e) {
                                                            e.printStackTrace();
                                                                    }
                                                                        }
                                                                        
                                                                        ```
                                                                        
                                                                        
                                                                        
                                                                        
                                                                        
                                                                        
                                                                        由于在框架中,我已经进行了封装,每个接口请求后都会返回 response 信息。所以一开始我想着从拿到 response 信息进行存储,查阅官方文档,寻找 response 信息获取的相关 API,发现 response.asString();可以获取到 json body 的信息,就先尝试使用。
                                                                        ```
                                                                        //// Get the response body as a String
                                                                        response.asString();
                                                                        
                                                                        // Get all headers
                                                                        Headers allHeaders = response.getHeaders();
                                                                        // Get a single header value:
                                                                        String headerName = response.getHeader("headerName");
                                                                        
                                                                        // Get all cookies as simple name-value pairs
                                                                        Map<String, String> allCookies = response.getCookies();
                                                                        // Get a single cookie value:
                                                                        String cookieValue = response.getCookie("cookieName");
                                                                        
                                                                        // Get status line
                                                                        String statusLine = response.getStatusLine();
                                                                        // Get status code
                                                                        int statusCode = response.getStatusCode();
                                                                        
                                                                        ```
                                                                        
                                                                        - 先创建方法,用于接收 response 获取信息
                                                                        
                                                                        ```
                                                                        @Attachment("响应报文")
                                                                        public static String respondBody(Response response) {
                                                                        
                                                                        
                                                                            boolean prettyFormat = true;
                                                                                JSONObject jsonObject = JSONObject.parseObject(response.asString());
                                                                                    String responseBody = JSONObject.toJSONString(jsonObject,prettyFormat);
                                                                                    
                                                                                    
                                                                                        return responseBody;
                                                                                        }
                                                                                        
                                                                                        ```
                                                                                        
                                                                                        
                                                                                        - 再创建方法,用于接收请求信息,由于我的所有请求信息都传入了一个 Restful 对象中且未找到 Rest-assured 关于请求信息直接获取的 API,这里我就直接取 Restful对象
                                                                                        Restful对象:
                                                                                        ```
                                                                                        import lombok.Data;
                                                                                        import java.util.HashMap;
                                                                                        
                                                                                        @Data
                                                                                        public class Restful {
                                                                                        
                                                                                            public String url;
                                                                                                public String method;
                                                                                                    public HashMap<String,Object> header = new HashMap<>();
                                                                                                        public HashMap<String,Object> query = new HashMap<>();
                                                                                                            public HashMap<String,Object> pathQuery = new HashMap<>();
                                                                                                                public String body;
                                                                                                                }
                                                                                                                
                                                                                                                ```
                                                                                                                
                                                                                                                
                                                                                                                ```
                                                                                                                @Attachment("请求信息")
                                                                                                                public static String requestBody(Restful restful) {
                                                                                                                    //报告展现请求信息
                                                                                                                        return restful.toString();
                                                                                                                        }
                                                                                                                        
                                                                                                                        ```
                                                                                                                        
                                                                                                                        
                                                                                                                        - 最后创建一个总的接收方法加入请求流程中,在每个请求结束后获取日志信息进行附件添加
                                                                                                                        
                                                                                                                        ```
                                                                                                                        public static void getRequestAndRespondBody(Restful restful, Response response){
                                                                                                                                requestBody(restful);
                                                                                                                                        respondBody(response);
                                                                                                                                            }
                                                                                                                                            
                                                                                                                                            ```
                                                                                                                                            
                                                                                                                                            
                                                                                                                                            从结果可以看到请求和响应报文已经成功展示,说明这种实现的思路的可行性,只是展示的日志信息还不满意,还是先想要全部的请求和响应信息且是格式化后的,不仅仅只有报文,继续探索~
                                                                                                                                            
                                                                                                                                            
                                                                                                                                            
                                                                                                                                            在研究过程中发现RestAssured提供了logConfig方法,可以将原本在Console中打印的信息指定格式化输出到文件中,具体用法如下(这里指演示重点实现原理部分,其余封装细节太冗余就不展示了):
                                                                                                                                            - WriterOutputStream用到依赖如下:
                                                                                                                                            
                                                                                                                                            ```
                                                                                                                                            <dependency>
                                                                                                                                                <groupId>commons-io</groupId>
                                                                                                                                                    <artifactId>commons-io</artifactId>
                                                                                                                                                        <version>2.4</version>
                                                                                                                                                        </dependency>
                                                                                                                                                        
                                                                                                                                                        ```
                                                                                                                                                        
                                                                                                                                                        - 在请求中设置log打印方式和存储路径
                                                                                                                                                        
                                                                                                                                                        ```
                                                                                                                                                        public void addLogToFile(){
                                                                                                                                                          try (FileWriter fileWriter = new FileWriter("src/main/resources/test.log");
                                                                                                                                                                 PrintStream printStream = new PrintStream(new WriterOutputStream(fileWriter), true)) {
                                                                                                                                                                        RestAssured.config = RestAssured.config().logConfig(LogConfig.logConfig().defaultStream(printStream));
                                                                                                                                                                               given().XXX.log().all().
                                                                                                                                                                                      when().XXX
                                                                                                                                                                                             then().log().all();
                                                                                                                                                                                               } catch (IOException e) {
                                                                                                                                                                                                      e.printStackTrace();
                                                                                                                                                                                                        }
                                                                                                                                                                                                        }
                                                                                                                                                                                                        
                                                                                                                                                                                                        ```
                                                                                                                                                                                                        
                                                                                                                                                                                                        
                                                                                                                                                                                                        - 创建附件添加方法加入请求流程中,在每个请求结束后获取日志信息进行附件添加
                                                                                                                                                                                                        
                                                                                                                                                                                                        ```
                                                                                                                                                                                                        public static void addHttpLogToAllure() {
                                                                                                                                                                                                           try {
                                                                                                                                                                                                                   Allure.addAttachment("接口请求响应日志",
                                                                                                                                                                                                                                   new FileInputStream("src/main/resources/test.log"));
                                                                                                                                                                                                                                       } catch (FileNotFoundException e) {
                                                                                                                                                                                                                                               e.printStackTrace();
                                                                                                                                                                                                                                                   }
                                                                                                                                                                                                                                                   }
                                                                                                                                                                                                                                                   
                                                                                                                                                                                                                                                   ```
                                                                                                                                                                                                                                                   
                                                                                                                                                                                                                                                   - 整体的流程思路就是:
                                                                                                                                                                                                                                                   
                                                                                                                                                                                                                                                   ```
                                                                                                                                                                                                                                                   @Test
                                                                                                                                                                                                                                                   void testAllureReport(){
                                                                                                                                                                                                                                                     addLogToFile();
                                                                                                                                                                                                                                                       addHttpLogToAllure();
                                                                                                                                                                                                                                                       }
                                                                                                                                                                                                                                                       
                                                                                                                                                                                                                                                       ```
                                                                                                                                                                                                                                                       
                                                                                                                                                                                                                                                       
                                                                                                                                                                                                                                                       在下面展示的用例中有2个接口请求,可以看到分别记录展示了,且格式与 Console 中格式化打印的保持一致。
                                                                                                                                                                                                                                                       
                                                                                                                                                                                                                                                       
                                                                                                                                                                                                                                                       Rest-assured 提供了过滤器 Filters,利用它可以串改请求,设置鉴权信息,过滤 log 等,具体的可在官网中进行学习研究,这里主要用到 RequestLoggingFilter()和 ResponseLoggingFilter() 来实现我们的需求。
                                                                                                                                                                                                                                                       RequestLoggingFilter() 和 ResponseLoggingFilter() 可以将所有的请求和响应的 log 进行打印,而我们想要的是将 log 存入文件,因此还要借助方法 logRequestTo(PrintStream stream),指定 log 的格式化输出到文件中:
                                                                                                                                                                                                                                                       ```
                                                                                                                                                                                                                                                       FileWriter fileWriter = null;
                                                                                                                                                                                                                                                       try {
                                                                                                                                                                                                                                                           fileWriter = new FileWriter("src/main/resources/test.log");
                                                                                                                                                                                                                                                           } catch (IOException e) {
                                                                                                                                                                                                                                                               e.printStackTrace();
                                                                                                                                                                                                                                                               }
                                                                                                                                                                                                                                                               PrintStream printStream = new PrintStream(new WriterOutputStream(fileWriter), true);
                                                                                                                                                                                                                                                               RestAssured.filters(new RequestLoggingFilter().logRequestTo(printStream),new ResponseLoggingFilter().logResponseTo(printStream));
                                                                                                                                                                                                                                                               
                                                                                                                                                                                                                                                               ```
                                                                                                                                                                                                                                                               
                                                                                                                                                                                                                                                               附件添加复用上述的方法:
                                                                                                                                                                                                                                                               ```
                                                                                                                                                                                                                                                               AllureAttachment.addHttpLogToAllure();
                                                                                                                                                                                                                                                               
                                                                                                                                                                                                                                                               ```
                                                                                                                                                                                                                                                               
                                                                                                                                                                                                                                                               
                                                                                                                                                                                                                                                               
                                                                                                                                                                                                                                                               结果依然实现了我们的需求
                                                                                                                                                                                                                                                               
                                                                                                                                                                                                                                                               
                                                                                                                                                                                                                                                               
                                                                                                                                                                                                                                                               高效测试开发实战技能进阶提升?推荐霍格沃兹测试学院出品的 《测试开发从入门到高级实战》系统进阶班,可能是业界最具深度、最贴近大厂一线实践的测试开发课程。
                                                                                                                                                                                                                                                               
                                                                                                                                                                                                                                                               4 个月由浅入深,强化集训,测试大咖思寒领衔主讲,授之以渔,通过 10+ 企业级项目实战演练,带你一站式掌握 BAT 测试开发工程师必备核心技能(对标阿里巴巴P6+,挑战年薪50W+)!学员直推 BAT 名企测试经理,普遍涨薪 50%+!
                                                                                                                                                                                                                                                               
                                                                                                                                                                                                                                                               
                                                                                                                                                                                                                                                               12期热招中,入群获取完整版大纲
                                                                                                                                                                                                                                                               
                                                                                                                                                                                                                                                               推荐阅读
                                                                                                                                                                                                                                                               ## 提升自己的核心竞争力吧!
                                                                                                                                                                                                                                                               [原文链接](https://mp.weixin.qq.com/s?__biz=MzU3NDM4ODEzMg==&mid=2247487948&idx=1&sn=70851f7b46894af4f77b9784610b2532&chksm=fd327307ca45fa1191e36bdadfe906df3d59e6e40cb22809a25b41e125a52be2d78f771e5338#rd) 
                                                                                                                                                                                                                                                               
                                                                                                                                                                                                                                                               [更多技术文章](https://qrcode.ceba.ceshiren.com/link?name=article&project_id=qrcode&from=juejin&timestamp=1661965200&author=Muller)