如何使用Testng框架将可靠的控制台日志写入redable或txt文件?

问题描述 投票:1回答:2

我是Java的新手,请放心,我无法在脚本中添加将控制台日志打印到可读文件的方法。我试图使用Log4j,但我无法正确实现它。我在研究时发现了这一点,但我不确定如何实施 - https://static.javadoc.io/com.jayway.restassured/rest-assured/2.7.0/com/jayway/restassured/config/LogConfig.html

import static io.restassured.RestAssured.given;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;

import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import files.reusableFunctions;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.path.xml.XmlPath;
import io.restassured.response.Response;

public class Playlist_Acknowledgement {

    Properties prop = new Properties(); // creating prop object as global

    @BeforeTest
    public void testData1() throws Exception {

        FileInputStream f = new FileInputStream("D:\\Tools\\Workspace\\BXF\\src\\files\\config.properties");
        prop.load(f); // to load the file object into prop file

        reusableFunctions rf = new reusableFunctions();
        rf.createBxfPlaylistXml();
    }

    @SuppressWarnings("unused")
    @Test
    public void postData() throws IOException {


        String pth = prop.getProperty("PLAYLISTACK_ENDPOINT");
        File path = new File(pth);

        File[] files = path.listFiles();
        for (int i = 0; i < files.length; i++) {

            pth = files[i].toString();
            System.out.println("Path = " + pth);
            String postData = new String(Files.readAllBytes(Paths.get(pth)));
            // BaseURL
            // value populating from property above
            RestAssured.baseURI = prop.getProperty("AISHOST");

            Response resp = given().log().all()
                    .header("Content-Type", "application/XML; charset=utf-8")
                    .body(postData)
                    .when().post("/bxfxml")
                    .then().log().all()
                    .assertThat()
                    .statusCode(200).and()
                    .contentType(ContentType.XML)
                    .extract().response();


            // to convert raw data to string
            XmlPath xmlResponse = reusableFunctions.rawToXML(resp);
            String responseString = resp.asString();
            System.out.println("XML response is - " + responseString);
            // Files.delete(files[i].toPath());
            // Files.copy(path.toPath(), prop.getProperty(key) );
        }
    }
}
java rest-assured
2个回答
1
投票

您可以按如下方式设置配置

LogConfig logconfig = new LogConfig().enableLoggingOfRequestAndResponseIfValidationFails().enablePrettyPrinting(true);
RestAssured.config().logConfig(logconfig);

然后你可以继续你的常规

RestAssured.given().log().all()
        .header("Content-Type", "application/XML; charset=utf-8")
        .body("")
        .when().post("/bxfxml")
        .then().log().all()
        .assertThat()
        .statusCode(200).and()
        .contentType(ContentType.XML)
        .extract().response();

0
投票

考虑使用log4j 2库。它提供了一个库来为记录器创建流。

使用log4j-iostreams构建PrintStream。将其设置为RestAssured logConfig的输出流


0
投票
ByteArrayOutputStream requestStream = new ByteArrayOutputStream();
        ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
        PrintStream requestPrint = new PrintStream(requestStream);
        PrintStream responsePrint = new PrintStream(responseStream);
        RequestLoggingFilter requestLoggingFilter = new RequestLoggingFilter(LogDetail.ALL,false,requestPrint);;
        ResponseLoggingFilter responseLoggingFilter = new ResponseLoggingFilter(LogDetail.ALL,false,responsePrint);
        RestAssured.filters(requestLoggingFilter,responseLoggingFilter);
        Response response = given().body("{\"name\":\""+ UUID.randomUUID().toString() +"\",\"salary\":\"123\",\"age\":\"23\"}").post("http://dummy.restapiexample.com/api/v1/create");
        String req = requestStream.toString();
        String res = responseStream.toString();

        System.out.print("\r\n" + "----------------------------------------Request Data----------------------------------------" + "\r\n");
        System.out.println(req);
        System.out.print("\r\n" + "----------------------------------------End Request Data-----------------------------------" + "\r\n");
        System.out.print("\r\n" + "----------------------------------------Response Data----------------------------------------" + "\r\n");
        System.out.println("Duration in Milliseconds:" + response.time());
        System.out.println(res);
        System.out.print("\r\n" + "----------------------------------------End Response Data-----------------------------------" + "\r\n");
        requestStream.reset();
        responseStream.reset();

Sample output:
-------------------------------------Request Data----------------------------------------
Request method: POST
Request URI:    http://dummy.restapiexample.com/api/v1/create
Proxy:          <none>
Request params: <none>
Query params:   <none>
Form params:    <none>
Path params:    <none>
Headers:        Accept=*/*
                Content-Type=text/plain; charset=ISO-8859-1
Cookies:        <none>
Multiparts:     <none>
Body:
{"name":"b77704de-90cb-4b58-bdc2-c3dd8693c395","salary":"123","age":"23"}


----------------------------------------End Request Data-----------------------------------

----------------------------------------Response Data----------------------------------------
Duration in Milliseconds:654
HTTP/1.1 200 OK
Date: Thu, 11 Jul 2019 05:07:27 GMT
Server: Apache
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: Content-Type, X-Requested-With, X-authentication, X-client
Set-Cookie: PHPSESSID=72d7f71b4a7a6d29b42228276124c3b0; path=/
Upgrade: h2,h2c
Connection: Upgrade, Keep-Alive
Vary: Accept-Encoding
Content-Encoding: gzip
Referrer-Policy: 
Content-Length: 95
Keep-Alive: timeout=5, max=75
Content-Type: text/html; charset=UTF-8

{"name":"b77704de-90cb-4b58-bdc2-c3dd8693c395","salary":"123","age":"23","id":"5841"}


----------------------------------------End Response Data-----------------------------------

链接到完整实施https://github.com/johnson-phillips/qa.automation.api/blob/master/src/main/java/qa/automation/core/Api.java

© www.soinside.com 2019 - 2024. All rights reserved.