org.springframework.restdocs.constraints.ConstraintDescriptions Java Examples

The following examples show how to use org.springframework.restdocs.constraints.ConstraintDescriptions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Snippets.java    From genie with Apache License 2.0 6 votes vote down vote up
private static FieldDescriptor[] getBaseFieldDescriptors(final ConstraintDescriptions constraintDescriptions) {
    return new FieldDescriptor[]{
        PayloadDocumentation
            .fieldWithPath("id")
            .attributes(getConstraintsForField(constraintDescriptions, "id"))
            .description("The id. If not set the system will set one.")
            .type(JsonFieldType.STRING)
            .optional(),
        PayloadDocumentation
            .fieldWithPath("created")
            .attributes(getConstraintsForField(constraintDescriptions, "created"))
            .description("The UTC time of creation. Set by system. ISO8601 format including milliseconds.")
            .type(JsonFieldType.STRING)
            .optional(),
        PayloadDocumentation
            .fieldWithPath("updated")
            .attributes(getConstraintsForField(constraintDescriptions, "updated"))
            .description("The UTC time of last update. Set by system. ISO8601 format including milliseconds.")
            .type(JsonFieldType.STRING)
            .optional(),
    };
}
 
Example #2
Source File: ApiDocumentationJUnit4IntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void crudGetExample() throws Exception {

    Map<String, Object> crud = new HashMap<>();
    crud.put("id", 1L);
    crud.put("title", "Sample Model");
    crud.put("body", "http://www.baeldung.com/");

    String tagLocation = this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON)
        .content(this.objectMapper.writeValueAsString(crud)))
        .andExpect(status().isOk())
        .andReturn()
        .getResponse()
        .getHeader("Location");

    crud.put("tags", singletonList(tagLocation));

    ConstraintDescriptions desc = new ConstraintDescriptions(CrudInput.class);

    this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON)
        .content(this.objectMapper.writeValueAsString(crud)))
        .andExpect(status().isOk())
        .andDo(document("crud-get-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestFields(fieldWithPath("id").description("The id of the input" + collectionToDelimitedString(desc.descriptionsForProperty("id"), ". ")),
            fieldWithPath("title").description("The title of the input"), fieldWithPath("body").description("The body of the input"), fieldWithPath("tags").description("An array of tag resource URIs"))));
}
 
Example #3
Source File: ApiDocumentationJUnit5IntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void crudGetExample() throws Exception {

    Map<String, Object> crud = new HashMap<>();
    crud.put("id", 1L);
    crud.put("title", "Sample Model");
    crud.put("body", "http://www.baeldung.com/");

    String tagLocation = this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON)
        .content(this.objectMapper.writeValueAsString(crud)))
        .andExpect(status().isOk())
        .andReturn()
        .getResponse()
        .getHeader("Location");

    crud.put("tags", singletonList(tagLocation));

    ConstraintDescriptions desc = new ConstraintDescriptions(CrudInput.class);

    this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON)
        .content(this.objectMapper.writeValueAsString(crud)))
        .andExpect(status().isOk())
        .andDo(document("crud-get-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestFields(fieldWithPath("id").description("The id of the input" + collectionToDelimitedString(desc.descriptionsForProperty("id"), ". ")),
            fieldWithPath("title").description("The title of the input"), fieldWithPath("body").description("The body of the input"), fieldWithPath("tags").description("An array of tag resource URIs"))));
}
 
Example #4
Source File: SpringRestDocsUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenUpdateFoo_thenSuccessful() throws Exception {
    
    ConstraintDescriptions desc = new ConstraintDescriptions(Foo.class);

    Map<String, Object> foo = new HashMap<>();
    foo.put("title", "Updated Foo");
    foo.put("body", "Body of Updated Foo");

    this.mockMvc.perform(put("/foo/{id}", 3).contentType(MediaTypes.HAL_JSON)
        .content(this.objectMapper.writeValueAsString(foo)))
        .andExpect(status().isOk())
        .andDo(document("updateFoo", pathParameters(parameterWithName("id").description("The id of the foo to update")),
            responseFields(fieldWithPath("id").description("The id of the updated foo" + collectionToDelimitedString(desc.descriptionsForProperty("id"), ". ")),
                fieldWithPath("title").description("The title of the updated foo"), fieldWithPath("body").description("The body of the updated foo"))));
}
 
Example #5
Source File: UserMvcTests.java    From jakduk-api with MIT License 5 votes vote down vote up
@Test
@WithMockUser
public void resetPasswordTest() throws Exception {

    Map<String, Object> form = new HashMap<String, Object>() {{
        put("code", "16948f83-1af8-4736-9e12-cf57f03a981c");
        put("password", "1112");
    }};

    UserPasswordFindResponse expectResponse = new UserPasswordFindResponse(jakdukUser.getEmail(),
            JakdukUtils.getMessageSource("user.msg.success.change.password"));

    when(userService.resetPasswordWithToken(anyString(), anyString()))
            .thenReturn(expectResponse);

    ConstraintDescriptions userConstraints = new ConstraintDescriptions(UserPasswordResetForm.class, new ValidatorConstraintResolver(),
            new ResourceBundleConstraintDescriptionResolver(ResourceBundle.getBundle("ValidationMessages")));

    mvc.perform(
            post("/api/user/password/reset")
                    .contentType(MediaType.APPLICATION_JSON)
                    .with(csrf())
                    .content(ObjectMapperUtils.writeValueAsString(form)))
            .andExpect(status().isOk())
            .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
            .andExpect(content().json(ObjectMapperUtils.writeValueAsString(expectResponse)))
            .andDo(
                    document("user-reset-password",
                            requestFields(
                                    fieldWithPath("code").type(JsonFieldType.STRING).description("임시 발행한 토큰 코드. (5분간 유지) " +
                                            userConstraints.descriptionsForProperty("code")),
                                    fieldWithPath("password").type(JsonFieldType.STRING).description("바꿀 비밀번호 " +
                                            userConstraints.descriptionsForProperty("password"))
                            ),
                            responseFields(this.getPasswordFindDescriptor())
                    ));
}
 
Example #6
Source File: Snippets.java    From genie with Apache License 2.0 5 votes vote down vote up
private static Attributes.Attribute getConstraintsForField(
    final ConstraintDescriptions constraints,
    final String fieldName
) {
    return Attributes
        .key(CONSTRAINTS)
        .value(StringUtils.collectionToDelimitedString(constraints.descriptionsForProperty(fieldName), ". "));
}
 
Example #7
Source File: Snippets.java    From genie with Apache License 2.0 5 votes vote down vote up
private static FieldDescriptor[] getCommonFieldDescriptors(final ConstraintDescriptions constraintDescriptions) {
    return ArrayUtils.addAll(
        getBaseFieldDescriptors(constraintDescriptions),
        PayloadDocumentation
            .fieldWithPath("name")
            .attributes(getConstraintsForField(constraintDescriptions, "name"))
            .description("The name")
            .type(JsonFieldType.STRING),
        PayloadDocumentation
            .fieldWithPath("user")
            .attributes(getConstraintsForField(constraintDescriptions, "user"))
            .description("The user")
            .type(JsonFieldType.STRING),
        PayloadDocumentation
            .fieldWithPath("version")
            .attributes(getConstraintsForField(constraintDescriptions, "version"))
            .description("The version")
            .type(JsonFieldType.STRING),
        PayloadDocumentation
            .fieldWithPath("description")
            .attributes(getConstraintsForField(constraintDescriptions, "description"))
            .description("Any description")
            .type(JsonFieldType.STRING)
            .optional(),
        PayloadDocumentation
            .subsectionWithPath("metadata")
            .attributes(getConstraintsForField(constraintDescriptions, "metadata"))
            .description("Any semi-structured metadata. Must be valid JSON")
            .type(JsonFieldType.OBJECT)
            .optional(),
        PayloadDocumentation
            .fieldWithPath("tags")
            .attributes(getConstraintsForField(constraintDescriptions, "tags"))
            .description("The tags")
            .type(JsonFieldType.ARRAY)
            .optional()
    );
}
 
Example #8
Source File: Snippets.java    From genie with Apache License 2.0 5 votes vote down vote up
private static FieldDescriptor[] getSetupFieldDescriptors(final ConstraintDescriptions constraintDescriptions) {
    return ArrayUtils.addAll(
        getCommonFieldDescriptors(constraintDescriptions),
        PayloadDocumentation
            .fieldWithPath("setupFile")
            .attributes(getConstraintsForField(constraintDescriptions, "setupFile"))
            .description("A location for any setup that needs to be done when installing")
            .type(JsonFieldType.STRING)
            .optional()
    );
}
 
Example #9
Source File: Snippets.java    From genie with Apache License 2.0 5 votes vote down vote up
private static FieldDescriptor[] getConfigFieldDescriptors(final ConstraintDescriptions constraintDescriptions) {
    return ArrayUtils.addAll(
        getSetupFieldDescriptors(constraintDescriptions),
        PayloadDocumentation
            .fieldWithPath("configs")
            .attributes(getConstraintsForField(constraintDescriptions, "configs"))
            .description("Any configuration files needed for the resource")
            .type(JsonFieldType.ARRAY)
            .optional()
    );
}
 
Example #10
Source File: SpringRestDocsUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenGetFooById_thenSuccessful() throws Exception {
    ConstraintDescriptions desc = new ConstraintDescriptions(Foo.class);

    this.mockMvc.perform(get("/foo/{id}", 1))
        .andExpect(status().isOk())
        .andDo(document("getAFoo", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), 
            pathParameters(parameterWithName("id").description("id of foo to be searched")),
            responseFields(fieldWithPath("id").description("The id of the foo" + collectionToDelimitedString(desc.descriptionsForProperty("id"), ". ")),
            fieldWithPath("title").description("The title of the foo"), fieldWithPath("body").description("The body of the foo"))));
}
 
Example #11
Source File: UserMvcTests.java    From jakduk-api with MIT License 5 votes vote down vote up
@Test
@WithAnonymousUser
public void findPasswordTest() throws Exception {

    Map<String, Object> form = new HashMap<String, Object>() {{
        put("email", jakdukUser.getEmail());
        put("callbackUrl", "http://dev-wev.jakduk/find/password");
    }};

    UserPasswordFindResponse expectResponse = new UserPasswordFindResponse(form.get("email").toString(),
            JakdukUtils.getMessageSource("user.msg.reset.password.send.email"));

    when(userService.sendEmailToResetPassword(anyString(), anyString()))
            .thenReturn(expectResponse);

    ConstraintDescriptions userConstraints = new ConstraintDescriptions(UserPasswordFindForm.class, new ValidatorConstraintResolver(),
            new ResourceBundleConstraintDescriptionResolver(ResourceBundle.getBundle("ValidationMessages")));

    mvc.perform(
            post("/api/user/password/find")
                    .contentType(MediaType.APPLICATION_JSON)
                    .with(csrf())
                    .content(ObjectMapperUtils.writeValueAsString(form)))
            .andExpect(status().isOk())
            .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
            .andExpect(content().json(ObjectMapperUtils.writeValueAsString(expectResponse)))
            .andDo(
                    document("user-find-password",
                            requestFields(
                                    fieldWithPath("email").type(JsonFieldType.STRING).description("이메일 주소. " +
                                            userConstraints.descriptionsForProperty("email")),
                                    fieldWithPath("callbackUrl").type(JsonFieldType.STRING).description("콜백 받을 URL. " +
                                            userConstraints.descriptionsForProperty("callbackUrl"))
                            ),
                            responseFields(this.getPasswordFindDescriptor())
                    ));
}
 
Example #12
Source File: ArticleMvcTests.java    From jakduk-api with MIT License 5 votes vote down vote up
private FieldDescriptor[] getWriteArticleFormDescriptor() {
    ConstraintDescriptions userConstraints = new ConstraintDescriptions(WriteArticle.class);

    return new FieldDescriptor[] {
            fieldWithPath("subject").type(JsonFieldType.STRING).description("글 제목. " + userConstraints.descriptionsForProperty("subject")),
            fieldWithPath("content").type(JsonFieldType.STRING).description("글 내용. " + userConstraints.descriptionsForProperty("content")),
            fieldWithPath("categoryCode").type(JsonFieldType.STRING)
                    .description("(optional, default ALL) 말머리. board가 FREE 일때에는 무시된다. FOOTBALL, DEVELOPER일 때에는 필수다."),
            subsectionWithPath("galleries").type(JsonFieldType.ARRAY).description("(optional) 그림 목록")
    };
}
 
Example #13
Source File: ArticleCommentMvcTests.java    From jakduk-api with MIT License 5 votes vote down vote up
private FieldDescriptor[] getWriteArticleCommentFormDescriptor() {
    ConstraintDescriptions userConstraints = new ConstraintDescriptions(WriteArticleComment.class);

    return new FieldDescriptor[] {
            fieldWithPath("content").type(JsonFieldType.STRING).description("댓글 내용. " + userConstraints.descriptionsForProperty("content")),
            subsectionWithPath("galleries").type(JsonFieldType.ARRAY).description("(optional) 그림 목록")
    };
}
 
Example #14
Source File: ControllerTestTemplate.java    From coderadar with MIT License 5 votes vote down vote up
ConstrainedFields(Class<T> input) {

      try {
        this.constraintDescriptions = new ConstraintDescriptions(input);
        this.customValidationDescription.load(
            getClass()
                .getClassLoader()
                .getResourceAsStream("CustomValidationDescription.properties"));
      } catch (IOException e) {
        throw new IllegalArgumentException(
            "unable to load properties for custom validation description");
      }
    }
 
Example #15
Source File: ConstraintReaderImpl.java    From spring-auto-restdocs with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getConstraintMessages(Class<?> javaBaseClass, String javaFieldName) {
    ConstraintDescriptions constraints = new ConstraintDescriptions(javaBaseClass,
            constraintResolver, constraintAndGroupDescriptionResolver);
    List<String> constraintMessages = new ArrayList<>();
    constraintMessages.addAll(constraints.descriptionsForProperty(javaFieldName));
    constraintMessages.addAll(getEnumConstraintMessage(javaBaseClass, javaFieldName));
    return constraintMessages;
}
 
Example #16
Source File: ConstrainedFields.java    From springrestdoc with MIT License 4 votes vote down vote up
public ConstrainedFields(Class<?> input) {
    this.constraintDescriptions = new ConstraintDescriptions(input);
}
 
Example #17
Source File: AuthMvcTests.java    From jakduk-api with MIT License 4 votes vote down vote up
@Test
@WithMockUser
public void snsLoginTest() throws Exception {

    Map<String, Object> requestForm = new HashMap<String, Object>() {{
        put("accessToken", "baada13b7df9af000fa20355bf07b25f808940ab69dd7f32b6c009efdd0f6d29");
    }};

    when(authUtils.getSnsProfile(any(Constants.ACCOUNT_TYPE.class), anyString()))
            .thenReturn(socialProfile);

    Optional<User> optUser = Optional.of(
            new User() {{
                setId("58b2dbf1d6d83b04bf365277");
                setEmail("[email protected]");
                setUsername("생글이");
                setProviderId(providerId);
                setProviderUserId(socialProfile.getId());
                setRoles(Arrays.asList(JakdukAuthority.ROLE_USER_01.getCode()));
                setAbout("안녕하세요.");
            }}
    );

    when(userService.findOneByProviderIdAndProviderUserId(any(Constants.ACCOUNT_TYPE.class), anyString()))
            .thenReturn(optUser);

    ConstraintDescriptions loginSocialUserConstraints = new ConstraintDescriptions(LoginSocialUserForm.class);

    mvc.perform(
            post("/api/auth/login/{providerId}", providerId)
                    .contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON)
                    .content(ObjectMapperUtils.writeValueAsString(requestForm))
                    .with(csrf()))
            .andExpect(status().isOk())
            .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
            .andExpect(content().json(ObjectMapperUtils.writeValueAsString(EmptyJsonResponse.newInstance())))
            .andDo(
                    document("login-sns-user",
                            pathParameters(
                                    parameterWithName("providerId").description("SNS 분류 " +
                                            Stream.of(Constants.ACCOUNT_TYPE.values())
                                                    .filter(accountType -> ! accountType.equals(Constants.ACCOUNT_TYPE.JAKDUK))
                                                    .map(Enum::name)
                                                    .map(String::toLowerCase)
                                                    .collect(Collectors.toList())
                                    )
                            ),
                            requestFields(
                                    fieldWithPath("accessToken").type(JsonFieldType.STRING).description("OAuth의 Access Token " +
                                            loginSocialUserConstraints.descriptionsForProperty("accessToken"))
                            ),
                            responseHeaders(
                                    headerWithName("Set-Cookie").description("인증 쿠키. value는 JSESSIONID=키값").optional()
                            )
                    ));
}
 
Example #18
Source File: UserMvcTests.java    From jakduk-api with MIT License 4 votes vote down vote up
@Test
@WithMockJakdukUser
public void editPasswordTest() throws Exception {

    when(userService.findUserOnPasswordUpdateById(anyString()))
            .thenReturn(new UserOnPasswordUpdate(jakdukUser.getId(), jakdukUser.getPassword()));

    Map<String, Object> form = new HashMap<String, Object>() {{
        put("password", "1111");
        put("newPassword", "1112");
        put("newPasswordConfirm", "1112");
    }};

    doNothing().when(userService)
            .updateUserPassword(anyString(), anyString());

    ConstraintDescriptions userConstraints = new ConstraintDescriptions(UserPasswordForm.class, new ValidatorConstraintResolver(),
            new ResourceBundleConstraintDescriptionResolver(ResourceBundle.getBundle("ValidationMessages")));

    mvc.perform(
            put("/api/user/password")
                    .cookie(new Cookie("JSESSIONID", "3F0E029648484BEAEF6B5C3578164E99"))
                    .contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON)
                    .with(csrf())
                    .content(ObjectMapperUtils.writeValueAsString(form)))
            .andExpect(status().isOk())
            .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
            .andExpect(content().json(ObjectMapperUtils.writeValueAsString(EmptyJsonResponse.newInstance())))
            .andDo(
                    document("user-edit-password",
                            requestHeaders(
                                    headerWithName("Cookie").optional().description("인증 쿠키. value는 JSESSIONID=키값")
                            ),
                            requestFields(
                                    fieldWithPath("password").type(JsonFieldType.STRING).description("현재 비밀번호. " +
                                            userConstraints.descriptionsForProperty("password")),
                                    fieldWithPath("newPassword").type(JsonFieldType.STRING).description("새 비밀번호. " +
                                            userConstraints.descriptionsForProperty("newPassword")),
                                    fieldWithPath("newPasswordConfirm").type(JsonFieldType.STRING).description("확인 새 비밀번호. " +
                                            userConstraints.descriptionsForProperty("newPasswordConfirm"))
                            )
                    ));
}
 
Example #19
Source File: UserMvcTests.java    From jakduk-api with MIT License 4 votes vote down vote up
@Test
@WithMockJakdukUser
public void editProfileMeTest() throws Exception {

    when(userProfileRepository.findByNEIdAndEmail(anyString(), anyString()))
            .thenReturn(Optional.empty());

    when(userProfileRepository.findByNEIdAndUsername(anyString(), anyString()))
            .thenReturn(Optional.empty());

    Map<String, Object> form = new HashMap<String, Object>() {{
        put("email", jakdukUser.getEmail());
        put("username", jakdukUser.getUsername());
        put("about", jakdukUser.getAbout());
        put("footballClub", footballClub.getId());
        put("userPictureId", userPicture.getId());
    }};

    when(userService.editUserProfile(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
            .thenReturn(jakdukUser);

    ConstraintDescriptions userConstraints = new ConstraintDescriptions(UserProfileEditForm.class, new ValidatorConstraintResolver(),
            new ResourceBundleConstraintDescriptionResolver(ResourceBundle.getBundle("ValidationMessages")));

    mvc.perform(
            put("/api/user/profile/me")
                    .cookie(new Cookie("JSESSIONID", "3F0E029648484BEAEF6B5C3578164E99"))
                    .contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON)
                    .with(csrf())
                    .content(ObjectMapperUtils.writeValueAsString(form)))
            .andExpect(status().isOk())
            .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
            .andExpect(content().json(ObjectMapperUtils.writeValueAsString(EmptyJsonResponse.newInstance())))
            .andDo(
                    document("user-edit-profile-me",
                            requestHeaders(
                                    headerWithName("Cookie").optional().description("인증 쿠키. value는 JSESSIONID=키값")
                            ),
                            requestFields(
                                    fieldWithPath("email").type(JsonFieldType.STRING).description("이메일 주소. " +
                                            userConstraints.descriptionsForProperty("email")),
                                    fieldWithPath("username").type(JsonFieldType.STRING).description("별명. " +
                                            userConstraints.descriptionsForProperty("username")),
                                    fieldWithPath("footballClub").type(JsonFieldType.STRING).description("(optional) 축구단 ID"),
                                    fieldWithPath("about").type(JsonFieldType.STRING).description("(optional) 자기 소개"),
                                    fieldWithPath("userPictureId").type(JsonFieldType.STRING).description("(optional) 프로필 사진 ID")
                            )
                    ));
}
 
Example #20
Source File: UserMvcTests.java    From jakduk-api with MIT License 4 votes vote down vote up
@Test
@WithMockUser
public void createSocialUserTest() throws Exception {

    this.whenCustomValdation();

    AttemptSocialUser attemptSocialUser = new AttemptSocialUser();
    attemptSocialUser.setUsername("daumUser01");
    attemptSocialUser.setProviderId(Constants.ACCOUNT_TYPE.FACEBOOK);
    attemptSocialUser.setProviderUserId("abc123");
    attemptSocialUser.setExternalSmallPictureUrl("https://img1.daumcdn.net/thumb/R55x55/?fname=http%3A%2F%2Ftwg.tset.daumcdn.net%2Fprofile%2F6enovyMT1pI0&t=1507478752861");
    attemptSocialUser.setExternalLargePictureUrl("https://img1.daumcdn.net/thumb/R158x158/?fname=http%3A%2F%2Ftwg.tset.daumcdn.net%2Fprofile%2F6enovyMT1pI0&t=1507478752861");

    MockHttpSession mockHttpSession = new MockHttpSession();
    mockHttpSession.setAttribute(Constants.PROVIDER_SIGNIN_ATTEMPT_SESSION_ATTRIBUTE, attemptSocialUser);

    SocialUserForm form = new SocialUserForm();
    form.setEmail("[email protected]");
    form.setUsername("SocialUser");
    form.setAbout("안녕하세요.");
    form.setFootballClub(footballClub.getId());
    form.setUserPictureId(userPicture.getId());
    form.setExternalLargePictureUrl("https://img1.daumcdn.net/thumb/R158x158/?fname=http%3A%2F%2Ftwg.tset.daumcdn.net%2Fprofile%2FSjuNejHmr8o0&t=1488000722876");

    User expectUser = new User();
    expectUser.setId("597df86caaf4fc0545d4f3e9");
    expectUser.setEmail(form.getEmail());
    expectUser.setUsername(form.getUsername());
    expectUser.setPassword("841db2bc28e4730906bd82d79e69c80633747570d96ffade7dd77f58270f31a222e129e005cb70d2");
    expectUser.setProviderId(attemptSocialUser.getProviderId());
    expectUser.setProviderUserId(attemptSocialUser.getProviderUserId());
    expectUser.setAbout(form.getAbout());
    expectUser.setRoles(Arrays.asList(JakdukAuthority.ROLE_USER_02.getCode()));
    expectUser.setSupportFC(footballClub);
    expectUser.setLastLogged(LocalDateTime.now());

    when(userService.createSocialUser(anyString(), anyString(), any(Constants.ACCOUNT_TYPE.class), anyString(),
            anyString(), anyString(), anyString(), anyString()))
            .thenReturn(expectUser);

    ConstraintDescriptions userConstraints = new ConstraintDescriptions(SocialUserForm.class, new ValidatorConstraintResolver(),
            new ResourceBundleConstraintDescriptionResolver(ResourceBundle.getBundle("ValidationMessages")));

    mvc.perform(
            post("/api/user/social")
                    .session(mockHttpSession)
                    .contentType(MediaType.APPLICATION_JSON)
                    .with(csrf())
                    .content(ObjectMapperUtils.writeValueAsString(form)))
            .andExpect(status().isOk())
            .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
            .andExpect(content().json(ObjectMapperUtils.writeValueAsString(EmptyJsonResponse.newInstance())))
            .andDo(
                    document("create-sns-user",
                            requestFields(
                                    fieldWithPath("email").type(JsonFieldType.STRING).description("이메일 주소. " +
                                            userConstraints.descriptionsForProperty("email")),
                                    fieldWithPath("username").type(JsonFieldType.STRING).description("별명. " +
                                            userConstraints.descriptionsForProperty("username")),
                                    fieldWithPath("footballClub").type(JsonFieldType.STRING).description("(optional) 축구단 ID"),
                                    fieldWithPath("about").type(JsonFieldType.STRING).description("(optional) 자기 소개"),
                                    fieldWithPath("userPictureId").type(JsonFieldType.STRING).description("(optional) 프로필 사진 ID"),
                                    fieldWithPath("externalLargePictureUrl").type(JsonFieldType.STRING)
                                            .description("(optional) SNS계정에서 제공하는 회원 큰 사진 URL. userPictureId가 null 이어야 한다.")
                            ),
                            responseHeaders(
                                    headerWithName("Set-Cookie").description("인증 쿠키. value는 JSESSIONID=키값").optional()
                            )
                    ));
}
 
Example #21
Source File: UserMvcTests.java    From jakduk-api with MIT License 4 votes vote down vote up
@Test
@WithAnonymousUser
public void createJakdukUserTest() throws Exception {

    this.whenCustomValdation();

    UserForm form = new UserForm();
    form.setEmail(jakdukUser.getEmail());
    form.setUsername(jakdukUser.getUsername());
    form.setPassword("1111");
    form.setPasswordConfirm("1111");
    form.setAbout(jakdukUser.getAbout());
    form.setFootballClub(footballClub.getId());
    form.setUserPictureId(userPicture.getId());

    when(userService.createJakdukUser(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
            .thenReturn(jakdukUser);

    ConstraintDescriptions userConstraints = new ConstraintDescriptions(UserForm.class, new ValidatorConstraintResolver(),
            new ResourceBundleConstraintDescriptionResolver(ResourceBundle.getBundle("ValidationMessages")));

    mvc.perform(
            post("/api/user")
                    .contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON)
                    .with(csrf())
                    .content(ObjectMapperUtils.writeValueAsString(form)))
            .andExpect(status().isOk())
            .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
            .andExpect(content().json(ObjectMapperUtils.writeValueAsString(EmptyJsonResponse.newInstance())))
            .andDo(
                    document("create-jakduk-user",
                            requestFields(
                                    fieldWithPath("email").type(JsonFieldType.STRING).description("이메일 주소. " +
                                            userConstraints.descriptionsForProperty("email")),
                                    fieldWithPath("username").type(JsonFieldType.STRING).description("별명. " +
                                            userConstraints.descriptionsForProperty("username")),
                                    fieldWithPath("password").type(JsonFieldType.STRING).description("비밀번호. " +
                                            userConstraints.descriptionsForProperty("password")),
                                    fieldWithPath("passwordConfirm").type(JsonFieldType.STRING).description("확인 비밀번호. " +
                                            userConstraints.descriptionsForProperty("passwordConfirm")),
                                    fieldWithPath("footballClub").type(JsonFieldType.STRING).description("(optional) 축구단 ID"),
                                    fieldWithPath("about").type(JsonFieldType.STRING).description("(optional) 자기 소개"),
                                    fieldWithPath("userPictureId").type(JsonFieldType.STRING).description("(optional) 프로필 사진 ID")
                            ),
                            responseHeaders(
                                    headerWithName("Set-Cookie").description("인증 쿠키. value는 JSESSIONID=키값").optional()
                            )
                    ));
}
 
Example #22
Source File: ApiDocumentation.java    From restdocs-wiremock with Apache License 2.0 4 votes vote down vote up
ConstrainedFields(Class<?> input) {
	this.constraintDescriptions = new ConstraintDescriptions(input);
}