refactor the integration test lib to use the index resource & add unit tests for autoComplete permission

This commit is contained in:
Mohamed Karray
2018-10-15 18:35:45 +02:00
parent e891ce9850
commit 356b84f4cd
7 changed files with 229 additions and 439 deletions

View File

@@ -24,67 +24,33 @@ public class AutoCompleteITCase {
} }
@Test @Test
public void adminShouldAutoCompleteUsers() { public void adminShouldAutoComplete() {
createUsers(); shouldAutocomplete(TestData.USER_SCM_ADMIN, TestData.USER_SCM_ADMIN);
ScmRequests.start()
.given()
.requestIndexResource(TestData.USER_SCM_ADMIN,TestData.USER_SCM_ADMIN)
.assertStatusCode(200)
.usingIndexResponse()
.requestAutoCompleteUsers("user*")
.assertStatusCode(200)
.usingAutoCompleteResponse()
.assertAutoCompleteResults(assertAutoCompleteResult(CREATED_USER_PREFIX));
} }
@Test @Test
public void userShouldAutoCompleteUsersWithoutAdminPermission() { public void userShouldAutoComplete() {
String username = "nonAdmin"; String username = "nonAdmin";
String password = "pass"; String password = "pass";
TestData.createUser(username, password, false, "xml", "email@e.de"); TestData.createUser(username, password, false, "xml", "email@e.de");
shouldAutocomplete(username, password);
}
public void shouldAutocomplete(String username, String password) {
createUsers(); createUsers();
createGroups();
ScmRequests.start() ScmRequests.start()
.given() .requestIndexResource(username, password)
.requestIndexResource(username,password)
.assertStatusCode(200) .assertStatusCode(200)
.usingIndexResponse() .requestAutoCompleteGroups("group*")
.assertStatusCode(200)
.assertAutoCompleteResults(assertAutoCompleteResult(CREATED_GROUP_PREFIX))
.returnToPrevious()
.requestAutoCompleteUsers("user*") .requestAutoCompleteUsers("user*")
.assertStatusCode(200) .assertStatusCode(200)
.usingAutoCompleteResponse()
.assertAutoCompleteResults(assertAutoCompleteResult(CREATED_USER_PREFIX)); .assertAutoCompleteResults(assertAutoCompleteResult(CREATED_USER_PREFIX));
} }
@Test
public void adminShouldAutoCompleteGroups() {
createGroups();
ScmRequests.start()
.given()
.requestIndexResource(TestData.USER_SCM_ADMIN,TestData.USER_SCM_ADMIN)
.assertStatusCode(200)
.usingIndexResponse()
.applyAutoCompleteGroups("group*")
.assertStatusCode(200)
.usingAutoCompleteResponse()
.assertAutoCompleteResults(assertAutoCompleteResult(CREATED_GROUP_PREFIX));
}
@Test
public void userShouldAutoCompleteGroupsWithoutAdminPermission() {
String username = "nonAdminUser";
String password = "pass";
TestData.createNotAdminUser(username, password);
createGroups();
ScmRequests.start()
.given()
.requestIndexResource(username,password)
.assertStatusCode(200)
.usingIndexResponse()
.applyAutoCompleteGroups("group*")
.assertStatusCode(200)
.usingAutoCompleteResponse()
.assertAutoCompleteResults(assertAutoCompleteResult(CREATED_GROUP_PREFIX));
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private Consumer<List<Map>> assertAutoCompleteResult(String id) { private Consumer<List<Map>> assertAutoCompleteResult(String id) {
return autoCompleteDtos -> { return autoCompleteDtos -> {

View File

@@ -20,12 +20,9 @@ public class MeITCase {
String newPassword = TestData.USER_SCM_ADMIN + "1"; String newPassword = TestData.USER_SCM_ADMIN + "1";
// admin change the own password // admin change the own password
ScmRequests.start() ScmRequests.start()
.given() .requestIndexResource(TestData.USER_SCM_ADMIN, TestData.USER_SCM_ADMIN)
.url(TestData.getMeUrl()) .requestMe()
.usernameAndPassword(TestData.USER_SCM_ADMIN, TestData.USER_SCM_ADMIN)
.getMeResource()
.assertStatusCode(200) .assertStatusCode(200)
.usingMeResponse()
.assertAdmin(aBoolean -> assertThat(aBoolean).isEqualTo(Boolean.TRUE)) .assertAdmin(aBoolean -> assertThat(aBoolean).isEqualTo(Boolean.TRUE))
.assertPassword(Assert::assertNull) .assertPassword(Assert::assertNull)
.assertType(s -> assertThat(s).isEqualTo("xml")) .assertType(s -> assertThat(s).isEqualTo("xml"))
@@ -33,12 +30,9 @@ public class MeITCase {
.assertStatusCode(204); .assertStatusCode(204);
// assert password is changed -> login with the new Password than undo changes // assert password is changed -> login with the new Password than undo changes
ScmRequests.start() ScmRequests.start()
.given() .requestIndexResource(TestData.USER_SCM_ADMIN, newPassword)
.url(TestData.getUserUrl(TestData.USER_SCM_ADMIN)) .requestMe()
.usernameAndPassword(TestData.USER_SCM_ADMIN, newPassword)
.getMeResource()
.assertStatusCode(200) .assertStatusCode(200)
.usingMeResponse()
.assertAdmin(aBoolean -> assertThat(aBoolean).isEqualTo(Boolean.TRUE))// still admin .assertAdmin(aBoolean -> assertThat(aBoolean).isEqualTo(Boolean.TRUE))// still admin
.requestChangePassword(newPassword, TestData.USER_SCM_ADMIN) .requestChangePassword(newPassword, TestData.USER_SCM_ADMIN)
.assertStatusCode(204); .assertStatusCode(204);
@@ -51,12 +45,9 @@ public class MeITCase {
String type = "not XML Type"; String type = "not XML Type";
TestData.createUser(newUser, password, true, type, "user@scm-manager.org"); TestData.createUser(newUser, password, true, type, "user@scm-manager.org");
ScmRequests.start() ScmRequests.start()
.given() .requestIndexResource(newUser, password)
.url(TestData.getMeUrl()) .requestMe()
.usernameAndPassword(newUser, password)
.getMeResource()
.assertStatusCode(200) .assertStatusCode(200)
.usingMeResponse()
.assertAdmin(aBoolean -> assertThat(aBoolean).isEqualTo(Boolean.TRUE)) .assertAdmin(aBoolean -> assertThat(aBoolean).isEqualTo(Boolean.TRUE))
.assertPassword(Assert::assertNull) .assertPassword(Assert::assertNull)
.assertType(s -> assertThat(s).isEqualTo(type)) .assertType(s -> assertThat(s).isEqualTo(type))

View File

@@ -44,7 +44,7 @@ public class RepositoryAccessITCase {
private final String repositoryType; private final String repositoryType;
private File folder; private File folder;
private ScmRequests.AppliedRepositoryRequest repositoryGetRequest; private ScmRequests.RepositoryResponse<ScmRequests.IndexResponse> repositoryResponse;
public RepositoryAccessITCase(String repositoryType) { public RepositoryAccessITCase(String repositoryType) {
this.repositoryType = repositoryType; this.repositoryType = repositoryType;
@@ -59,17 +59,13 @@ public class RepositoryAccessITCase {
public void init() { public void init() {
TestData.createDefault(); TestData.createDefault();
folder = tempFolder.getRoot(); folder = tempFolder.getRoot();
repositoryGetRequest = ScmRequests.start() String namespace = ADMIN_USERNAME;
.given() String repo = TestData.getDefaultRepoName(repositoryType);
.url(TestData.getDefaultRepositoryUrl(repositoryType)) repositoryResponse =
.usernameAndPassword(ADMIN_USERNAME, ADMIN_PASSWORD) ScmRequests.start()
.getRepositoryResource() .requestIndexResource(ADMIN_USERNAME, ADMIN_PASSWORD)
.requestRepository(namespace, repo)
.assertStatusCode(HttpStatus.SC_OK); .assertStatusCode(HttpStatus.SC_OK);
ScmRequests.AppliedMeRequest meGetRequest = ScmRequests.start()
.given()
.url(TestData.getMeUrl())
.usernameAndPassword(ADMIN_USERNAME, ADMIN_PASSWORD)
.getMeResource();
} }
@Test @Test
@@ -306,17 +302,12 @@ public class RepositoryAccessITCase {
public void shouldFindFileHistory() throws IOException { public void shouldFindFileHistory() throws IOException {
RepositoryClient repositoryClient = RepositoryUtil.createRepositoryClient(repositoryType, folder); RepositoryClient repositoryClient = RepositoryUtil.createRepositoryClient(repositoryType, folder);
Changeset changeset = RepositoryUtil.createAndCommitFile(repositoryClient, ADMIN_USERNAME, "folder/subfolder/a.txt", "a"); Changeset changeset = RepositoryUtil.createAndCommitFile(repositoryClient, ADMIN_USERNAME, "folder/subfolder/a.txt", "a");
repositoryGetRequest repositoryResponse
.usingRepositoryResponse()
.requestSources() .requestSources()
.usingSourcesResponse()
.requestSelf("folder") .requestSelf("folder")
.usingSourcesResponse()
.requestSelf("subfolder") .requestSelf("subfolder")
.usingSourcesResponse()
.requestFileHistory("a.txt") .requestFileHistory("a.txt")
.assertStatusCode(HttpStatus.SC_OK) .assertStatusCode(HttpStatus.SC_OK)
.usingChangesetsResponse()
.assertChangesets(changesets -> { .assertChangesets(changesets -> {
assertThat(changesets).hasSize(1); assertThat(changesets).hasSize(1);
assertThat(changesets.get(0)).containsEntry("id", changeset.getId()); assertThat(changesets.get(0)).containsEntry("id", changeset.getId());
@@ -332,14 +323,11 @@ public class RepositoryAccessITCase {
String fileName = "a.txt"; String fileName = "a.txt";
Changeset changeset = RepositoryUtil.createAndCommitFile(repositoryClient, ADMIN_USERNAME, fileName, "a"); Changeset changeset = RepositoryUtil.createAndCommitFile(repositoryClient, ADMIN_USERNAME, fileName, "a");
String revision = changeset.getId(); String revision = changeset.getId();
repositoryGetRequest repositoryResponse
.usingRepositoryResponse()
.requestChangesets() .requestChangesets()
.assertStatusCode(HttpStatus.SC_OK) .assertStatusCode(HttpStatus.SC_OK)
.usingChangesetsResponse()
.requestModifications(revision) .requestModifications(revision)
.assertStatusCode(HttpStatus.SC_OK) .assertStatusCode(HttpStatus.SC_OK)
.usingModificationsResponse()
.assertRevision(actualRevision -> assertThat(actualRevision).isEqualTo(revision)) .assertRevision(actualRevision -> assertThat(actualRevision).isEqualTo(revision))
.assertAdded(addedFiles -> assertThat(addedFiles) .assertAdded(addedFiles -> assertThat(addedFiles)
.hasSize(1) .hasSize(1)
@@ -359,14 +347,11 @@ public class RepositoryAccessITCase {
Changeset changeset = RepositoryUtil.removeAndCommitFile(repositoryClient, ADMIN_USERNAME, fileName); Changeset changeset = RepositoryUtil.removeAndCommitFile(repositoryClient, ADMIN_USERNAME, fileName);
String revision = changeset.getId(); String revision = changeset.getId();
repositoryGetRequest repositoryResponse
.usingRepositoryResponse()
.requestChangesets() .requestChangesets()
.assertStatusCode(HttpStatus.SC_OK) .assertStatusCode(HttpStatus.SC_OK)
.usingChangesetsResponse()
.requestModifications(revision) .requestModifications(revision)
.assertStatusCode(HttpStatus.SC_OK) .assertStatusCode(HttpStatus.SC_OK)
.usingModificationsResponse()
.assertRevision(actualRevision -> assertThat(actualRevision).isEqualTo(revision)) .assertRevision(actualRevision -> assertThat(actualRevision).isEqualTo(revision))
.assertRemoved(removedFiles -> assertThat(removedFiles) .assertRemoved(removedFiles -> assertThat(removedFiles)
.hasSize(1) .hasSize(1)
@@ -386,14 +371,11 @@ public class RepositoryAccessITCase {
Changeset changeset = RepositoryUtil.createAndCommitFile(repositoryClient, ADMIN_USERNAME, fileName, "new Content"); Changeset changeset = RepositoryUtil.createAndCommitFile(repositoryClient, ADMIN_USERNAME, fileName, "new Content");
String revision = changeset.getId(); String revision = changeset.getId();
repositoryGetRequest repositoryResponse
.usingRepositoryResponse()
.requestChangesets() .requestChangesets()
.assertStatusCode(HttpStatus.SC_OK) .assertStatusCode(HttpStatus.SC_OK)
.usingChangesetsResponse()
.requestModifications(revision) .requestModifications(revision)
.assertStatusCode(HttpStatus.SC_OK) .assertStatusCode(HttpStatus.SC_OK)
.usingModificationsResponse()
.assertRevision(actualRevision -> assertThat(actualRevision).isEqualTo(revision)) .assertRevision(actualRevision -> assertThat(actualRevision).isEqualTo(revision))
.assertModified(modifiedFiles -> assertThat(modifiedFiles) .assertModified(modifiedFiles -> assertThat(modifiedFiles)
.hasSize(1) .hasSize(1)
@@ -423,14 +405,11 @@ public class RepositoryAccessITCase {
Changeset changeset = RepositoryUtil.commitMultipleFileModifications(repositoryClient, ADMIN_USERNAME, addedFiles, modifiedFiles, removedFiles); Changeset changeset = RepositoryUtil.commitMultipleFileModifications(repositoryClient, ADMIN_USERNAME, addedFiles, modifiedFiles, removedFiles);
String revision = changeset.getId(); String revision = changeset.getId();
repositoryGetRequest repositoryResponse
.usingRepositoryResponse()
.requestChangesets() .requestChangesets()
.assertStatusCode(HttpStatus.SC_OK) .assertStatusCode(HttpStatus.SC_OK)
.usingChangesetsResponse()
.requestModifications(revision) .requestModifications(revision)
.assertStatusCode(HttpStatus.SC_OK) .assertStatusCode(HttpStatus.SC_OK)
.usingModificationsResponse()
.assertRevision(actualRevision -> assertThat(actualRevision).isEqualTo(revision)) .assertRevision(actualRevision -> assertThat(actualRevision).isEqualTo(revision))
.assertAdded(a -> assertThat(a) .assertAdded(a -> assertThat(a)
.hasSize(1) .hasSize(1)
@@ -463,14 +442,11 @@ public class RepositoryAccessITCase {
Changeset changeset = RepositoryUtil.commitMultipleFileModifications(repositoryClient, ADMIN_USERNAME, addedFiles, modifiedFiles, removedFiles); Changeset changeset = RepositoryUtil.commitMultipleFileModifications(repositoryClient, ADMIN_USERNAME, addedFiles, modifiedFiles, removedFiles);
String revision = changeset.getId(); String revision = changeset.getId();
repositoryGetRequest repositoryResponse
.usingRepositoryResponse()
.requestChangesets() .requestChangesets()
.assertStatusCode(HttpStatus.SC_OK) .assertStatusCode(HttpStatus.SC_OK)
.usingChangesetsResponse()
.requestModifications(revision) .requestModifications(revision)
.assertStatusCode(HttpStatus.SC_OK) .assertStatusCode(HttpStatus.SC_OK)
.usingModificationsResponse()
.assertRevision(actualRevision -> assertThat(actualRevision).isEqualTo(revision)) .assertRevision(actualRevision -> assertThat(actualRevision).isEqualTo(revision))
.assertAdded(a -> assertThat(a) .assertAdded(a -> assertThat(a)
.hasSize(3) .hasSize(3)

View File

@@ -23,27 +23,21 @@ public class UserITCase {
String newPassword = "new_password"; String newPassword = "new_password";
// admin change the own password // admin change the own password
ScmRequests.start() ScmRequests.start()
.given() .requestIndexResource(newUser, password)
.url(TestData.getUserUrl(newUser)) .assertStatusCode(200)
.usernameAndPassword(newUser, password) .requestUser(newUser)
.getUserResource()
.assertStatusCode(200) .assertStatusCode(200)
.usingUserResponse()
.assertAdmin(aBoolean -> assertThat(aBoolean).isEqualTo(Boolean.TRUE)) .assertAdmin(aBoolean -> assertThat(aBoolean).isEqualTo(Boolean.TRUE))
.assertPassword(Assert::assertNull) .assertPassword(Assert::assertNull)
.requestChangePassword(newPassword) // the oldPassword is not needed in the user resource .requestChangePassword(newPassword) // the oldPassword is not needed in the user resource
.assertStatusCode(204); .assertStatusCode(204);
// assert password is changed -> login with the new Password // assert password is changed -> login with the new Password
ScmRequests.start() ScmRequests.start()
.given() .requestIndexResource(newUser, newPassword)
.url(TestData.getUserUrl(newUser))
.usernameAndPassword(newUser, newPassword)
.getUserResource()
.assertStatusCode(200) .assertStatusCode(200)
.usingUserResponse() .requestUser(newUser)
.assertAdmin(isAdmin -> assertThat(isAdmin).isEqualTo(Boolean.TRUE)) .assertAdmin(isAdmin -> assertThat(isAdmin).isEqualTo(Boolean.TRUE))
.assertPassword(Assert::assertNull); .assertPassword(Assert::assertNull);
} }
@Test @Test
@@ -54,22 +48,19 @@ public class UserITCase {
String newPassword = "new_password"; String newPassword = "new_password";
// admin change the password of the user // admin change the password of the user
ScmRequests.start() ScmRequests.start()
.given() .requestIndexResource(TestData.USER_SCM_ADMIN, TestData.USER_SCM_ADMIN)
.url(TestData.getUserUrl(newUser))// the admin get the user object .assertStatusCode(200)
.usernameAndPassword(TestData.USER_SCM_ADMIN, TestData.USER_SCM_ADMIN) .requestUser(newUser)
.getUserResource()
.assertStatusCode(200) .assertStatusCode(200)
.usingUserResponse()
.assertAdmin(aBoolean -> assertThat(aBoolean).isEqualTo(Boolean.TRUE)) // the user anonymous is not an admin .assertAdmin(aBoolean -> assertThat(aBoolean).isEqualTo(Boolean.TRUE)) // the user anonymous is not an admin
.assertPassword(Assert::assertNull) .assertPassword(Assert::assertNull)
.requestChangePassword(newPassword) // the oldPassword is not needed in the user resource .requestChangePassword(newPassword) // the oldPassword is not needed in the user resource
.assertStatusCode(204); .assertStatusCode(204);
// assert password is changed // assert password is changed
ScmRequests.start() ScmRequests.start()
.given() .requestIndexResource(newUser, newPassword)
.url(TestData.getUserUrl(newUser)) .assertStatusCode(200)
.usernameAndPassword(newUser, newPassword) .requestUser(newUser)
.getUserResource()
.assertStatusCode(200); .assertStatusCode(200);
} }
@@ -82,12 +73,10 @@ public class UserITCase {
String type = "not XML Type"; String type = "not XML Type";
TestData.createUser(newUser, password, true, type, "user@scm-manager.org"); TestData.createUser(newUser, password, true, type, "user@scm-manager.org");
ScmRequests.start() ScmRequests.start()
.given() .requestIndexResource(newUser, password)
.url(TestData.getMeUrl()) .assertStatusCode(200)
.usernameAndPassword(newUser, password) .requestUser(newUser)
.getUserResource()
.assertStatusCode(200) .assertStatusCode(200)
.usingUserResponse()
.assertAdmin(aBoolean -> assertThat(aBoolean).isEqualTo(Boolean.TRUE)) .assertAdmin(aBoolean -> assertThat(aBoolean).isEqualTo(Boolean.TRUE))
.assertPassword(Assert::assertNull) .assertPassword(Assert::assertNull)
.assertType(s -> assertThat(s).isEqualTo(type)) .assertType(s -> assertThat(s).isEqualTo(type))

View File

@@ -4,7 +4,6 @@ import io.restassured.RestAssured;
import io.restassured.response.Response; import io.restassured.response.Response;
import sonia.scm.web.VndMediaType; import sonia.scm.web.VndMediaType;
import java.net.URI;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.function.Consumer; import java.util.function.Consumer;
@@ -33,8 +32,10 @@ public class ScmRequests {
return new ScmRequests(); return new ScmRequests();
} }
public Given given() { public IndexResponse requestIndexResource(String username, String password) {
return new Given(); setUsername(username);
setPassword(password);
return new IndexResponse(applyGETRequest(RestUtil.REST_BASE_URL.toString()));
} }
@@ -54,28 +55,28 @@ public class ScmRequests {
* *
* @param linkPropertyName the property name of link * @param linkPropertyName the property name of link
* @param response the response containing the link * @param response the response containing the link
* @param queryParams query params eg. ?q=xyz&count=12 * @param params query params eg. ?q=xyz&count=12 or path params eg. namespace/name
* @return the response of the GET request using the given link * @return the response of the GET request using the given link
*/ */
private Response applyGETRequestFromLinkWithParams(Response response, String linkPropertyName, String queryParams) { private Response applyGETRequestFromLinkWithParams(Response response, String linkPropertyName, String params) {
return applyGETRequestWithQueryParams(response return applyGETRequestWithQueryParams(response
.then() .then()
.extract() .extract()
.path(linkPropertyName), queryParams); .path(linkPropertyName), params);
} }
/** /**
* Apply a GET Request to the given <code>url</code> and return the response. * Apply a GET Request to the given <code>url</code> and return the response.
* *
* @param url the url of the GET request * @param url the url of the GET request
* @param htmlQueryParams query params eg. ?q=xyz&count=12 * @param params query params eg. ?q=xyz&count=12 or path params eg. namespace/name
* @return the response of the GET request using the given <code>url</code> * @return the response of the GET request using the given <code>url</code>
*/ */
private Response applyGETRequestWithQueryParams(String url, String htmlQueryParams) { private Response applyGETRequestWithQueryParams(String url, String params) {
return RestAssured.given() return RestAssured.given()
.auth().preemptive().basic(username, password) .auth().preemptive().basic(username, password)
.when() .when()
.get(url + htmlQueryParams); .get(url + params);
} }
/** /**
@@ -123,11 +124,6 @@ public class ScmRequests {
.put(url); .put(url);
} }
private void setUrl(String url) {
this.url = url;
}
private void setUsername(String username) { private void setUsername(String username) {
this.username = username; this.username = username;
} }
@@ -136,308 +132,185 @@ public class ScmRequests {
this.password = password; this.password = password;
} }
private String getUrl() {
return url; public class IndexResponse extends ModelResponse<IndexResponse, IndexResponse> {
public static final String LINK_AUTOCOMPLETE_USERS = "_links.autocomplete.find{it.name=='users'}.href";
public static final String LINK_AUTOCOMPLETE_GROUPS = "_links.autocomplete.find{it.name=='groups'}.href";
public static final String LINK_REPOSITORIES = "_links.repositories.href";
private static final String LINK_ME = "_links.me.href";
private static final String LINK_USERS = "_links.users.href";
public IndexResponse(Response response) {
super(response, null);
} }
private String getUsername() { public AutoCompleteResponse<IndexResponse> requestAutoCompleteUsers(String q) {
return username; return new AutoCompleteResponse<>(applyGETRequestFromLinkWithParams(response, LINK_AUTOCOMPLETE_USERS, "?q=" + q), this);
} }
private String getPassword() { public AutoCompleteResponse<IndexResponse> requestAutoCompleteGroups(String q) {
return password; return new AutoCompleteResponse<>(applyGETRequestFromLinkWithParams(response, LINK_AUTOCOMPLETE_GROUPS, "?q=" + q), this);
} }
public class Given { public RepositoryResponse<IndexResponse> requestRepository(String namespace, String name) {
return new RepositoryResponse<>(applyGETRequestFromLinkWithParams(response, LINK_REPOSITORIES, namespace + "/" + name), this);
public GivenUrl url(String url) {
setUrl(url);
return new GivenUrl();
} }
public AppliedIndexResource requestIndexResource(String username, String password) { public MeResponse<IndexResponse> requestMe() {
setUsername(username); return new MeResponse<>(applyGETRequestFromLink(response, LINK_ME), this);
setPassword(password);
return new AppliedIndexResource(applyGETRequest(RestUtil.REST_BASE_URL.toString()));
} }
public GivenUrl url(URI url) { public UserResponse<IndexResponse> requestUser(String username) {
setUrl(url.toString()); return new UserResponse<>(applyGETRequestFromLinkWithParams(response, LINK_USERS, username), this);
return new GivenUrl();
} }
} }
public class GivenWithUrlAndAuth { public class RepositoryResponse<PREV extends ModelResponse> extends ModelResponse<RepositoryResponse<PREV>, PREV> {
public AppliedMeRequest getMeResource() {
return new AppliedMeRequest(applyGETRequest(url));
public static final String LINKS_SOURCES = "_links.sources.href";
public static final String LINKS_CHANGESETS = "_links.changesets.href";
public RepositoryResponse(Response response, PREV previousResponse) {
super(response, previousResponse);
} }
public AppliedUserRequest getUserResource() { public SourcesResponse<RepositoryResponse> requestSources() {
return new AppliedUserRequest(applyGETRequest(url)); return new SourcesResponse<>(applyGETRequestFromLink(response, LINKS_SOURCES), this);
} }
public AppliedRepositoryRequest getRepositoryResource() { public ChangesetsResponse<RepositoryResponse> requestChangesets() {
return new AppliedRepositoryRequest( return new ChangesetsResponse<>(applyGETRequestFromLink(response, LINKS_CHANGESETS), this);
applyGETRequest(url)
);
}
public AppliedAutoCompleteRequest getAutoCompleteResource() {
return new AppliedAutoCompleteRequest(
applyGETRequest(url)
);
}
}
public class AppliedRequest<SELF extends AppliedRequest> {
private Response response;
public AppliedRequest(Response response) {
this.response = response;
}
/**
* apply custom assertions to the actual response
*
* @param consumer consume the response in order to assert the content. the header, the payload etc..
* @return the self object
*/
public SELF assertResponse(Consumer<Response> consumer) {
consumer.accept(response);
return (SELF) this;
}
/**
* special assertion of the status code
*
* @param expectedStatusCode the expected status code
* @return the self object
*/
public SELF assertStatusCode(int expectedStatusCode) {
this.response.then().assertThat().statusCode(expectedStatusCode);
return (SELF) this;
} }
} }
public class AppliedRepositoryRequest extends AppliedRequest<AppliedRepositoryRequest> { public class ChangesetsResponse<PREV extends ModelResponse> extends ModelResponse<ChangesetsResponse<PREV>, PREV> {
public AppliedRepositoryRequest(Response response) { public ChangesetsResponse(Response response, PREV previousResponse) {
super(response); super(response, previousResponse);
}
public RepositoryResponse usingRepositoryResponse() {
return new RepositoryResponse(super.response);
}
}
public class RepositoryResponse {
private Response repositoryResponse;
public RepositoryResponse(Response repositoryResponse) {
this.repositoryResponse = repositoryResponse;
}
public AppliedSourcesRequest requestSources() {
return new AppliedSourcesRequest(applyGETRequestFromLink(repositoryResponse, "_links.sources.href"));
}
public AppliedChangesetsRequest requestChangesets() {
return new AppliedChangesetsRequest(applyGETRequestFromLink(repositoryResponse, "_links.changesets.href"));
}
}
public class AppliedChangesetsRequest extends AppliedRequest<AppliedChangesetsRequest> {
public AppliedChangesetsRequest(Response response) {
super(response);
}
public ChangesetsResponse usingChangesetsResponse() {
return new ChangesetsResponse(super.response);
}
}
public class ChangesetsResponse {
private Response changesetsResponse;
public ChangesetsResponse(Response changesetsResponse) {
this.changesetsResponse = changesetsResponse;
} }
public ChangesetsResponse assertChangesets(Consumer<List<Map>> changesetsConsumer) { public ChangesetsResponse assertChangesets(Consumer<List<Map>> changesetsConsumer) {
List<Map> changesets = changesetsResponse.then().extract().path("_embedded.changesets"); List<Map> changesets = response.then().extract().path("_embedded.changesets");
changesetsConsumer.accept(changesets); changesetsConsumer.accept(changesets);
return this; return this;
} }
public AppliedDiffRequest requestDiff(String revision) { public DiffResponse<ChangesetsResponse> requestDiff(String revision) {
return new AppliedDiffRequest(applyGETRequestFromLink(changesetsResponse, "_embedded.changesets.find{it.id=='" + revision + "'}._links.diff.href")); return new DiffResponse<>(applyGETRequestFromLink(response, "_embedded.changesets.find{it.id=='" + revision + "'}._links.diff.href"), this);
} }
public AppliedModificationsRequest requestModifications(String revision) { public ModificationsResponse<ChangesetsResponse> requestModifications(String revision) {
return new AppliedModificationsRequest(applyGETRequestFromLink(changesetsResponse, "_embedded.changesets.find{it.id=='" + revision + "'}._links.modifications.href")); return new ModificationsResponse<>(applyGETRequestFromLink(response, "_embedded.changesets.find{it.id=='" + revision + "'}._links.modifications.href"), this);
} }
} }
public class AppliedSourcesRequest extends AppliedRequest<AppliedSourcesRequest> {
public AppliedSourcesRequest(Response sourcesResponse) { public class SourcesResponse<PREV extends ModelResponse> extends ModelResponse<SourcesResponse<PREV>, PREV> {
super(sourcesResponse);
}
public SourcesResponse usingSourcesResponse() { public SourcesResponse(Response response, PREV previousResponse) {
return new SourcesResponse(super.response); super(response, previousResponse);
}
}
public class SourcesResponse {
private Response sourcesResponse;
public SourcesResponse(Response sourcesResponse) {
this.sourcesResponse = sourcesResponse;
} }
public SourcesResponse assertRevision(Consumer<String> assertRevision) { public SourcesResponse assertRevision(Consumer<String> assertRevision) {
String revision = sourcesResponse.then().extract().path("revision"); String revision = response.then().extract().path("revision");
assertRevision.accept(revision); assertRevision.accept(revision);
return this; return this;
} }
public SourcesResponse assertFiles(Consumer<List> assertFiles) { public SourcesResponse assertFiles(Consumer<List> assertFiles) {
List files = sourcesResponse.then().extract().path("files"); List files = response.then().extract().path("files");
assertFiles.accept(files); assertFiles.accept(files);
return this; return this;
} }
public AppliedChangesetsRequest requestFileHistory(String fileName) { public ChangesetsResponse<SourcesResponse> requestFileHistory(String fileName) {
return new AppliedChangesetsRequest(applyGETRequestFromLink(sourcesResponse, "_embedded.files.find{it.name=='" + fileName + "'}._links.history.href")); return new ChangesetsResponse<>(applyGETRequestFromLink(response, "_embedded.files.find{it.name=='" + fileName + "'}._links.history.href"), this);
} }
public AppliedSourcesRequest requestSelf(String fileName) { public SourcesResponse<SourcesResponse> requestSelf(String fileName) {
return new AppliedSourcesRequest(applyGETRequestFromLink(sourcesResponse, "_embedded.files.find{it.name=='" + fileName + "'}._links.self.href")); return new SourcesResponse<>(applyGETRequestFromLink(response, "_embedded.files.find{it.name=='" + fileName + "'}._links.self.href"), this);
} }
} }
public class AppliedDiffRequest extends AppliedRequest<AppliedDiffRequest> { public class ModificationsResponse<PREV extends ModelResponse> extends ModelResponse<ModificationsResponse<PREV>, PREV> {
public AppliedDiffRequest(Response response) { public ModificationsResponse(Response response, PREV previousResponse) {
super(response); super(response, previousResponse);
}
} }
public class GivenUrl { public ModificationsResponse<PREV> assertRevision(Consumer<String> assertRevision) {
String revision = response.then().extract().path("revision");
public GivenWithUrlAndAuth usernameAndPassword(String username, String password) {
setUsername(username);
setPassword(password);
return new GivenWithUrlAndAuth();
}
}
public class AppliedModificationsRequest extends AppliedRequest<AppliedModificationsRequest> {
public AppliedModificationsRequest(Response response) {
super(response);
}
public ModificationsResponse usingModificationsResponse() {
return new ModificationsResponse(super.response);
}
}
public class ModificationsResponse {
private Response resource;
public ModificationsResponse(Response resource) {
this.resource = resource;
}
public ModificationsResponse assertRevision(Consumer<String> assertRevision) {
String revision = resource.then().extract().path("revision");
assertRevision.accept(revision); assertRevision.accept(revision);
return this; return this;
} }
public ModificationsResponse assertAdded(Consumer<List<String>> assertAdded) { public ModificationsResponse<PREV> assertAdded(Consumer<List<String>> assertAdded) {
List<String> added = resource.then().extract().path("added"); List<String> added = response.then().extract().path("added");
assertAdded.accept(added); assertAdded.accept(added);
return this; return this;
} }
public ModificationsResponse assertRemoved(Consumer<List<String>> assertRemoved) { public ModificationsResponse<PREV> assertRemoved(Consumer<List<String>> assertRemoved) {
List<String> removed = resource.then().extract().path("removed"); List<String> removed = response.then().extract().path("removed");
assertRemoved.accept(removed); assertRemoved.accept(removed);
return this; return this;
} }
public ModificationsResponse assertModified(Consumer<List<String>> assertModified) { public ModificationsResponse<PREV> assertModified(Consumer<List<String>> assertModified) {
List<String> modified = resource.then().extract().path("modified"); List<String> modified = response.then().extract().path("modified");
assertModified.accept(modified); assertModified.accept(modified);
return this; return this;
} }
} }
public class AppliedMeRequest extends AppliedRequest<AppliedMeRequest> { public class MeResponse<PREV extends ModelResponse> extends UserResponse<PREV> {
public AppliedMeRequest(Response response) {
super(response);
}
public MeResponse usingMeResponse() {
return new MeResponse(super.response);
}
}
public class MeResponse extends UserResponse<MeResponse> {
public MeResponse(Response response) { public MeResponse(Response response, PREV previousResponse) {
super(response); super(response, previousResponse);
}
public AppliedChangePasswordRequest requestChangePassword(String oldPassword, String newPassword) {
return new AppliedChangePasswordRequest(applyPUTRequestFromLink(super.response, "_links.password.href", VndMediaType.PASSWORD_CHANGE, createPasswordChangeJson(oldPassword, newPassword)));
} }
} }
public class UserResponse<SELF extends UserResponse> extends ModelResponse<SELF> { public class UserResponse<PREV extends ModelResponse> extends ModelResponse<UserResponse<PREV>, PREV> {
public static final String LINKS_PASSWORD_HREF = "_links.password.href"; public static final String LINKS_PASSWORD_HREF = "_links.password.href";
public UserResponse(Response response) { public UserResponse(Response response, PREV previousResponse) {
super(response); super(response, previousResponse);
} }
public SELF assertPassword(Consumer<String> assertPassword) { public UserResponse<PREV> assertPassword(Consumer<String> assertPassword) {
return super.assertSingleProperty(assertPassword, "password"); return super.assertSingleProperty(assertPassword, "password");
} }
public SELF assertType(Consumer<String> assertType) { public UserResponse<PREV> assertType(Consumer<String> assertType) {
return assertSingleProperty(assertType, "type"); return assertSingleProperty(assertType, "type");
} }
public SELF assertAdmin(Consumer<Boolean> assertAdmin) { public UserResponse<PREV> assertAdmin(Consumer<Boolean> assertAdmin) {
return assertSingleProperty(assertAdmin, "admin"); return assertSingleProperty(assertAdmin, "admin");
} }
public SELF assertPasswordLinkDoesNotExists() { public UserResponse<PREV> assertPasswordLinkDoesNotExists() {
return assertPropertyPathDoesNotExists(LINKS_PASSWORD_HREF); return assertPropertyPathDoesNotExists(LINKS_PASSWORD_HREF);
} }
public SELF assertPasswordLinkExists() { public UserResponse<PREV> assertPasswordLinkExists() {
return assertPropertyPathExists(LINKS_PASSWORD_HREF); return assertPropertyPathExists(LINKS_PASSWORD_HREF);
} }
public AppliedChangePasswordRequest requestChangePassword(String newPassword) { public ChangePasswordResponse<UserResponse> requestChangePassword(String newPassword) {
return new AppliedChangePasswordRequest(applyPUTRequestFromLink(super.response, LINKS_PASSWORD_HREF, VndMediaType.PASSWORD_CHANGE, createPasswordChangeJson(null, newPassword))); return requestChangePassword(null, newPassword);
}
public ChangePasswordResponse<UserResponse> requestChangePassword(String oldPassword, String newPassword) {
return new ChangePasswordResponse<>(applyPUTRequestFromLink(super.response, LINKS_PASSWORD_HREF, VndMediaType.PASSWORD_CHANGE, createPasswordChangeJson(oldPassword, newPassword)), this);
} }
} }
@@ -446,12 +319,18 @@ public class ScmRequests {
/** /**
* encapsulate standard assertions over model properties * encapsulate standard assertions over model properties
*/ */
public class ModelResponse<SELF extends ModelResponse> { public class ModelResponse<SELF extends ModelResponse<SELF, PREV>, PREV extends ModelResponse> {
protected PREV previousResponse;
protected Response response; protected Response response;
public ModelResponse(Response response) { public ModelResponse(Response response, PREV previousResponse) {
this.response = response; this.response = response;
this.previousResponse = previousResponse;
}
public PREV returnToPrevious() {
return previousResponse;
} }
public <T> SELF assertSingleProperty(Consumer<T> assertSingleProperty, String propertyJsonPath) { public <T> SELF assertSingleProperty(Consumer<T> assertSingleProperty, String propertyJsonPath) {
@@ -475,46 +354,26 @@ public class ScmRequests {
assertProperties.accept(properties); assertProperties.accept(properties);
return (SELF) this; return (SELF) this;
} }
/**
* special assertion of the status code
*
* @param expectedStatusCode the expected status code
* @return the self object
*/
public SELF assertStatusCode(int expectedStatusCode) {
this.response.then().assertThat().statusCode(expectedStatusCode);
return (SELF) this;
}
} }
public class AppliedChangePasswordRequest extends AppliedRequest<AppliedChangePasswordRequest> { public class AutoCompleteResponse<PREV extends ModelResponse> extends ModelResponse<AutoCompleteResponse<PREV>, PREV> {
public AppliedChangePasswordRequest(Response response) { public AutoCompleteResponse(Response response, PREV previousResponse) {
super(response); super(response, previousResponse);
} }
} public AutoCompleteResponse<PREV> assertAutoCompleteResults(Consumer<List<Map>> checker) {
public class AppliedUserRequest extends AppliedRequest<AppliedUserRequest> {
public AppliedUserRequest(Response response) {
super(response);
}
public UserResponse usingUserResponse() {
return new UserResponse(super.response);
}
}
public class AppliedAutoCompleteRequest extends AppliedRequest<AppliedAutoCompleteRequest> {
public AppliedAutoCompleteRequest(Response response) {
super(response);
}
public AutoCompleteResponse usingAutoCompleteResponse() {
return new AutoCompleteResponse(super.response);
}
}
public class AutoCompleteResponse extends ModelResponse<AutoCompleteResponse> {
public AutoCompleteResponse(Response response) {
super(response);
}
public AutoCompleteResponse assertAutoCompleteResults(Consumer<List<Map>> checker) {
List<Map> result = response.then().extract().path(""); List<Map> result = response.then().extract().path("");
checker.accept(result); checker.accept(result);
return this; return this;
@@ -522,31 +381,18 @@ public class ScmRequests {
} }
public class AppliedIndexResource extends AppliedRequest<AppliedIndexResource> {
public AppliedIndexResource(Response response) { public class DiffResponse<PREV extends ModelResponse> extends ModelResponse<DiffResponse<PREV>, PREV> {
super(response);
public DiffResponse(Response response, PREV previousResponse) {
super(response, previousResponse);
}
} }
public IndexResponse usingIndexResponse() { public class ChangePasswordResponse<PREV extends ModelResponse> extends ModelResponse<ChangePasswordResponse<PREV>, PREV> {
return new IndexResponse(super.response);
}
} public ChangePasswordResponse(Response response, PREV previousResponse) {
super(response, previousResponse);
public class IndexResponse extends ModelResponse<IndexResponse> {
public static final String AUTOCOMPLETE_USERS = "_links.autocomplete.find{it.name=='users'}.href";
public static final String AUTOCOMPLETE_GROUPS = "_links.autocomplete.find{it.name=='groups'}.href";
public IndexResponse(Response response) {
super(response);
}
public AppliedAutoCompleteRequest requestAutoCompleteUsers(String q) {
return new AppliedAutoCompleteRequest(applyGETRequestFromLinkWithParams(response, AUTOCOMPLETE_USERS, "?q="+q));
}
public AppliedAutoCompleteRequest applyAutoCompleteGroups(String q) {
return new AppliedAutoCompleteRequest(applyGETRequestFromLinkWithParams(response, AUTOCOMPLETE_GROUPS, "?q="+q));
} }
} }
} }

View File

@@ -203,12 +203,16 @@ public class TestData {
return JSON_BUILDER return JSON_BUILDER
.add("contact", "zaphod.beeblebrox@hitchhiker.com") .add("contact", "zaphod.beeblebrox@hitchhiker.com")
.add("description", "Heart of Gold") .add("description", "Heart of Gold")
.add("name", "HeartOfGold-" + repositoryType) .add("name", getDefaultRepoName(repositoryType))
.add("archived", false) .add("archived", false)
.add("type", repositoryType) .add("type", repositoryType)
.build().toString(); .build().toString();
} }
public static String getDefaultRepoName(String repositoryType) {
return "HeartOfGold-" + repositoryType;
}
public static String getGroupJson(String groupname , String desc) { public static String getGroupJson(String groupname , String desc) {
return JSON_BUILDER return JSON_BUILDER
.add("name", groupname) .add("name", groupname)
@@ -216,10 +220,6 @@ public class TestData {
.build().toString(); .build().toString();
} }
public static URI getMeUrl() {
return RestUtil.createResourceUrl("me/");
}
public static URI getGroupsUrl() { public static URI getGroupsUrl() {
return RestUtil.createResourceUrl("groups/"); return RestUtil.createResourceUrl("groups/");
} }
@@ -228,18 +228,6 @@ public class TestData {
return RestUtil.createResourceUrl("users/"); return RestUtil.createResourceUrl("users/");
} }
public static URI getUserUrl(String username) {
return getUsersUrl().resolve(username);
}
public static URI getUsersAutoCompleteUrl(String query ) {
return RestUtil.createResourceUrl("autocomplete/users?q="+query);
}
public static URI getGroupsAutoCompleteUrl(String query ) {
return RestUtil.createResourceUrl("autocomplete/groups?q="+query);
}
public static String createPasswordChangeJson(String oldPassword, String newPassword) { public static String createPasswordChangeJson(String oldPassword, String newPassword) {
return JSON_BUILDER return JSON_BUILDER
.add("oldPassword", oldPassword) .add("oldPassword", oldPassword)

View File

@@ -1,16 +1,16 @@
package sonia.scm.api.v2.resources; package sonia.scm.api.v2.resources;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.subject.Subject; import com.github.sdorra.shiro.ShiroRule;
import org.apache.shiro.subject.support.SubjectThreadState; import com.github.sdorra.shiro.SubjectAware;
import org.apache.shiro.util.ThreadContext; import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.util.ThreadState;
import org.assertj.core.util.Lists; import org.assertj.core.util.Lists;
import org.jboss.resteasy.core.Dispatcher; import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.mock.MockHttpRequest; import org.jboss.resteasy.mock.MockHttpRequest;
import org.jboss.resteasy.mock.MockHttpResponse; import org.jboss.resteasy.mock.MockHttpResponse;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
@@ -43,16 +43,17 @@ import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks; import static org.mockito.MockitoAnnotations.initMocks;
import static sonia.scm.api.v2.resources.DispatcherMock.createDispatcher; import static sonia.scm.api.v2.resources.DispatcherMock.createDispatcher;
@SubjectAware(configuration = "classpath:sonia/scm/shiro-002.ini")
@RunWith(MockitoJUnitRunner.Silent.class) @RunWith(MockitoJUnitRunner.Silent.class)
public class AutoCompleteResourceTest { public class AutoCompleteResourceTest {
@Rule
public final ShiroRule shiroRule = new ShiroRule();
public static final String URL = "/" + AutoCompleteResource.PATH; public static final String URL = "/" + AutoCompleteResource.PATH;
private final Integer defaultLimit = Manager.DEFAULT_LIMIT; private final Integer defaultLimit = Manager.DEFAULT_LIMIT;
private Dispatcher dispatcher; private Dispatcher dispatcher;
private final Subject subject = mock(Subject.class);
private final ThreadState subjectThreadState = new SubjectThreadState(subject);
private XmlUserDAO userDao; private XmlUserDAO userDao;
private XmlGroupDAO groupDao; private XmlGroupDAO groupDao;
private XmlDatabase xmlDB; private XmlDatabase xmlDB;
@@ -75,9 +76,6 @@ public class AutoCompleteResourceTest {
GroupManager groupManager = new DefaultGroupManager(groupDao); GroupManager groupManager = new DefaultGroupManager(groupDao);
AutoCompleteResource autoCompleteResource = new AutoCompleteResource(mapper, userManager, groupManager); AutoCompleteResource autoCompleteResource = new AutoCompleteResource(mapper, userManager, groupManager);
dispatcher = createDispatcher(autoCompleteResource); dispatcher = createDispatcher(autoCompleteResource);
subjectThreadState.bind();
ThreadContext.bind(subject);
when(subject.isPermitted(any(String.class))).thenReturn(true);
} }
@After @After
@@ -85,19 +83,6 @@ public class AutoCompleteResourceTest {
ThreadContext.unbindSubject(); ThreadContext.unbindSubject();
} }
@Test
public void shouldGet400OnFailedParameterForUserSearch() throws Exception {
MockHttpRequest request = MockHttpRequest
.get("/" + AutoCompleteResource.PATH + "users")
.contentType(VndMediaType.AUTOCOMPLETE)
.accept(VndMediaType.AUTOCOMPLETE);
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
assertEquals(400, response.getStatus());
}
@Test @Test
public void shouldGet400IfParameterLengthLessThan2CharsForUserSearch() throws Exception { public void shouldGet400IfParameterLengthLessThan2CharsForUserSearch() throws Exception {
MockHttpRequest request = MockHttpRequest MockHttpRequest request = MockHttpRequest
@@ -112,6 +97,21 @@ public class AutoCompleteResourceTest {
} }
@Test @Test
@SubjectAware(username = "trillian", password = "secret")
public void shouldGet400OnFailedParameterForUserSearch() throws Exception {
MockHttpRequest request = MockHttpRequest
.get("/" + AutoCompleteResource.PATH + "users")
.contentType(VndMediaType.AUTOCOMPLETE)
.accept(VndMediaType.AUTOCOMPLETE);
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
assertEquals(400, response.getStatus());
}
@Test
@SubjectAware(username = "trillian", password = "secret")
public void shouldSearchUsers() throws Exception { public void shouldSearchUsers() throws Exception {
ArrayList<User> users = Lists.newArrayList(createMockUser("YuCantFindMe", "ha ha"), createMockUser("user1", "User 1"), createMockUser("user2", "User 2")); ArrayList<User> users = Lists.newArrayList(createMockUser("YuCantFindMe", "ha ha"), createMockUser("user1", "User 1"), createMockUser("user2", "User 2"));
String searched = "user"; String searched = "user";
@@ -134,6 +134,22 @@ public class AutoCompleteResourceTest {
} }
@Test @Test
@SubjectAware(username = "user_without_autocomplete_permission", password = "secret")
public void shouldGet403OnAutoCompleteUsers() throws Exception {
MockHttpRequest request = MockHttpRequest
.get("/" + AutoCompleteResource.PATH + "users?q=user" )
.contentType(VndMediaType.AUTOCOMPLETE)
.accept(VndMediaType.AUTOCOMPLETE);
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
assertEquals(HttpServletResponse.SC_FORBIDDEN, response.getStatus());
}
@Test
@SubjectAware(username = "trillian", password = "secret")
public void shouldSearchUsersWithDefaultLimitLength() throws Exception { public void shouldSearchUsersWithDefaultLimitLength() throws Exception {
List<User> userList = IntStream.range(0, 10).boxed().map(i -> createMockUser("user" + i, "User " + i)).collect(Collectors.toList()); List<User> userList = IntStream.range(0, 10).boxed().map(i -> createMockUser("user" + i, "User " + i)).collect(Collectors.toList());
when(xmlDB.values()).thenReturn(userList); when(xmlDB.values()).thenReturn(userList);
@@ -150,6 +166,7 @@ public class AutoCompleteResourceTest {
} }
@Test @Test
@SubjectAware(username = "trillian", password = "secret")
public void shouldGet400OnFailedParameterForGroupSearch() throws Exception { public void shouldGet400OnFailedParameterForGroupSearch() throws Exception {
MockHttpRequest request = MockHttpRequest MockHttpRequest request = MockHttpRequest
.get("/" + AutoCompleteResource.PATH + "groups") .get("/" + AutoCompleteResource.PATH + "groups")
@@ -163,6 +180,7 @@ public class AutoCompleteResourceTest {
} }
@Test @Test
@SubjectAware(username = "trillian", password = "secret")
public void shouldGet400IfParameterLengthLessThan2CharsForGroupSearch() throws Exception { public void shouldGet400IfParameterLengthLessThan2CharsForGroupSearch() throws Exception {
MockHttpRequest request = MockHttpRequest MockHttpRequest request = MockHttpRequest
.get("/" + AutoCompleteResource.PATH + "groups?q=a") .get("/" + AutoCompleteResource.PATH + "groups?q=a")
@@ -176,6 +194,7 @@ public class AutoCompleteResourceTest {
} }
@Test @Test
@SubjectAware(username = "trillian", password = "secret")
public void shouldSearchGroups() throws Exception { public void shouldSearchGroups() throws Exception {
ArrayList<Group> groups = Lists.newArrayList(createMockGroup("YuCantFindMe"), createMockGroup("group_1"), createMockGroup("group_2")); ArrayList<Group> groups = Lists.newArrayList(createMockGroup("YuCantFindMe"), createMockGroup("group_1"), createMockGroup("group_2"));
String searched = "group"; String searched = "group";
@@ -197,6 +216,21 @@ public class AutoCompleteResourceTest {
} }
@Test @Test
@SubjectAware(username = "user_without_autocomplete_permission", password = "secret")
public void shouldGet403OnAutoCompleteGroups() throws Exception {
MockHttpRequest request = MockHttpRequest
.get("/" + AutoCompleteResource.PATH + "groups?q=user" )
.contentType(VndMediaType.AUTOCOMPLETE)
.accept(VndMediaType.AUTOCOMPLETE);
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
assertEquals(HttpServletResponse.SC_FORBIDDEN, response.getStatus());
}
@Test
@SubjectAware(username = "trillian", password = "secret")
public void shouldSearchGroupsWithDefaultLimitLength() throws Exception { public void shouldSearchGroupsWithDefaultLimitLength() throws Exception {
List<Group> groups = IntStream.range(0, 10).boxed().map(i -> createMockGroup("group_" + i)).collect(Collectors.toList()); List<Group> groups = IntStream.range(0, 10).boxed().map(i -> createMockGroup("group_" + i)).collect(Collectors.toList());
when(xmlDB.values()).thenReturn(groups); when(xmlDB.values()).thenReturn(groups);