【问题标题】:How to set cookie with the request using rest assured?如何使用放心的请求设置cookie?
【发布时间】:2017-02-22 11:09:52
【问题描述】:

我需要自动化其余的 API。 API 受 Spring 安全性保护。

下面是验证代码:

Response response = given().auth()
                    .form(userName, password,   FormAuthConfig.springSecurity().withLoggingEnabled(new LogConfig(captor, true)))
                    .post("/home/xyz.html");

            Assert.assertTrue("Error occurs", response.statusCode() == 302);

            if (response.statusCode() == 302) {
                Cookie cookie = response.getDetailedCookie("JSESSIONID");
                result.actualFieldValue = "User Authenticated: Session ID ->" + cookie.getValue();
                System.out.println("Cookie set : "+cookie.getValue());
                apiTestSessionID = cookie.getValue();
            }

用户登录并返回302状态,表示重定向。我找到cookie并设置在一些全局变量中。

现在,我用请求设置 cookie:

RequestSpecification reqSpecification = new RequestSpecBuilder().addCookie("JSESSIONID", AbstractBaseClass.apiTestSessionID).build();

            Map<String, String> parameters = new HashMap<String, String>();
            parameters.put("cstmrID", "000N0961");
            parameters.put("pageNumber", "1");
            parameters.put("pageSize", "10");
            parameters.put("sortColumnName", "FIELD_NM");
            parameters.put("sortDir", "asc");
            parameters.put("filterColumnName1", "");
            parameters.put("filterColumnName2", "USER_UPDT_EMAIL_ID");
            parameters.put("filterValue2", "");

            reqSpecification.queryParams(parameters);

            Response response = given().spec(reqSpecification).when().get("/service/customerConfig").thenReturn();
            System.out.println(response.asString());

但作为回应,我得到了 登录页面 HTML。我无法理解我在哪里做错了。

假设:

  1. 由于 post 请求返回 302,我是否需要重定向到下一个 url,然后使用 cookie 执行 get 请求。
  2. 这是用请求设置 cookie 的正确方法吗?
  3. 我需要设置请求的标头吗?如果是,则以下是标题信息。我需要全部设置吗?

GET /example.com/abc.html HTTP/1.1 主机:example.com 连接: 保持活动缓存控制:max-age=0 升级不安全请求:1 用户代理:Mozilla/5.0(Windows NT 6.1;WOW64)AppleWebKit/537.36 (KHTML,如 Gecko) Chrome/55.0.2883.87 Safari/537.36 接受: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8 Accept-Encoding: gzip, deflate, sdch Accept-Language: en-US,en;q=0.8 Cookie:JSESSIONID=C70A69F1C60D93DC3F8AC564BDE3F4DE.lon2mcaqaapp002; __utma=185291189.2055499590.1460104969.1460104969.1460618428.2

【问题讨论】:

    标签: cookies http-post httpclient http-get rest-assured


    【解决方案1】:
    import io.restassured.RestAssured;
    import io.restassured.http.ContentType;
    import io.restassured.http.Cookies;
    
    private Cookie cookie;
    
    @BeforeClass
    public void exampleOfLogin() {
        String body = String.format("//json");
        cookies = RestAssured.given()
                .contentType(ContentType.JSON)
                .when()
                .body(body)
                .post("www.test_test.com")
                .then()
                .statusCode(200)
                .extract()
                .response()
                .getDetailedCookies();
    }
    
    @Test
    public void performActionsBasedOnCookies() {
    //set cookies before making a post request and check the returned status code
        RestAssured.given()
                .cookies(cookies)
                .contentType(ContentType.JSON)
                .when()
                .post("www.test_url.com")
                .then()
                .statusCode(200);
    }
    

    【讨论】:

    • 谢谢,这为我节省了很多时间,您需要将变量重命名为static private Cookies coockies
    • 非常有帮助。谢谢
    【解决方案2】:

    我也是 Rest Assured 的新手,但我刚刚编写了类似的测试。

    我建议你写一个私有的authenticate()方法:

    private static String authenticate() {
        given()
            .auth()
            .form(userName, password,FormAuthConfig.springSecurity().withLoggingEnabled(new LogConfig(captor, true)))
        when()
            .post("/home/xyz.html").
        thenReturn()
            .getDetailedCookie("JSESSIONID");
    }
    

    然后在请求中使用cookie:

    given()
        .cookie(authenticate())
    when()
        .get("/service/customerConfig").
    thenReturn();
    

    但我不知道你如何在这里查看statusCode

    使用.log().all() 查看日志也是一个好主意。

    【讨论】:

      【解决方案3】:

      我曾尝试使用 getDetailedCookies() 来检索身份验证/授权 cookie,并将其设置为 given().cookies(cookies).when().post(url)。

      但我无法检索授权所需的所有 cookie。

      这是我的做法。

      1. 我创建了一个实例变量

        导入 io.restassured.filter.cookie.CookieFilter

        CookieFilter 过滤器 = new CookieFilter();

      2. 在身份验证/授权调用中使用 cookieFilter

        RestAssured.given().filter(filter).body(body).post(url).andReturn();

      3. 在需要身份验证/授权 cookie 的请求中使用相同的过滤器。

        RestAssured.given().filter(filter).body(body).post(url);

      过滤器中填充了来自身份验证调用的所有 cookie。

      这里有一个基本代码来说明这个想法。您可以将其扩展到您的步骤定义

      import io.restassured.RestAssured;
      import io.restassured.filter.cookie.CookieFilter;
      import io.restassured.response.Response;
      import org.junit.Test;
      
      public class RestAssuredRunner {
      
          CookieFilter filter = new CookieFilter();
      
      
      
      
      @Test
          public  void testAuthenticatedRequest(String[] args) {
      
      
              String url = "http://mywebsitelogin.com";
              String body = "userId=1212&&password=232323";
              //Authentication request
              Response response = RestAssured.given().filter(filter).body(body).post(url).andReturn();
              //Request that needs authentication
              RestAssured.given().filter(filter).body(body).post(url);
          }
      
      
      }
      

      【讨论】:

        猜你喜欢
        • 2021-12-28
        • 1970-01-01
        • 2014-02-08
        • 2016-07-21
        • 2011-03-21
        • 2021-01-16
        • 2014-10-19
        • 1970-01-01
        相关资源
        最近更新 更多