java - Spring REST Docs: how to replace parameters -


in unit tests find

this.mockmvc   .perform(post("/authenticate")     .contenttype(mediatype.application_form_urlencoded)     .param("username", "user@example.com")     .param("password", "supersecretpassword"))   .andexpect(status().isok())   .anddo(document("preprocessed-request",     preprocessrequest(replacepattern(pattern.compile("supersecretpassword"), "xxx")))); 

cf. spring rest docs documentation

this generates build/generated-snippets/preprocessed-request/http-request.adoc content

[source,http] ---- post /authenticate http/1.1 content-type: application/x-www-form-urlencoded  username=user%40example.com&password=supersecretpassword ---- 

but expect password masked because of replacepattern():

[source,http] ---- post /authenticate http/1.1 content-type: application/x-www-form-urlencoded  username=user%40example.com&password=xxx ---- 

what can do?

the pattern replacement has no effect due unfortunate side-effect of how mockmvc handles request parameters. replacepattern acts on content, i.e. body of request, mockmvc doesn't include form-encoded parameters in body.

spring rest docs smart enough deal when it's generating snippets, e.g. form url encoded post request looks @ parameters figure out request's body should be. doesn't apply these same smarts when applying replacepattern.

you can still mask password using own operationpreprocessor changes parameter map. example:

private operationpreprocessor maskpassword() {     return new passwordmaskingpreprocessor(); }  private static class passwordmaskingpreprocessor implements operationpreprocessor {      @override     public operationrequest preprocess(operationrequest request) {         parameters parameters = new parameters();         parameters.putall(request.getparameters());         parameters.set("password", "xxx");         return new operationrequestfactory().create(request.geturi(),                 request.getmethod(), request.getcontent(), request.getheaders(),                 parameters, request.getparts());     }      @override     public operationresponse preprocess(operationresponse response) {         return response;     }  } 

you can use new preprocessor in place of replacepattern:

this.mockmvc   .perform(post("/authenticate")     .contenttype(mediatype.application_form_urlencoded)     .param("username", "user@example.com")     .param("password", "supersecretpassword"))   .andexpect(status().isok())   .anddo(document("preprocessed-request",     preprocessrequest(maskpassword()))); 

Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -