From: Sébastien Lesaint Date: Wed, 28 Aug 2019 13:09:50 +0000 (+0200) Subject: remove deprecated WsTester X-Git-Tag: 8.0~186 X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=a6482f8abb4105307822467fd69e92ca783d2db3;p=sonarqube.git remove deprecated WsTester --- diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/language/ws/ListAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/language/ws/ListAction.java index f5bd503a8c8..e5be3dc75dc 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/language/ws/ListAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/language/ws/ListAction.java @@ -36,11 +36,12 @@ import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.NewAction; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.text.JsonWriter; +import org.sonar.server.ws.WsAction; /** * @since 5.1 */ -public class ListAction implements RequestHandler { +public class ListAction implements RequestHandler, WsAction { private static final String MATCH_ALL = ".*"; private final Languages languages; @@ -63,7 +64,7 @@ public class ListAction implements RequestHandler { } } - void define(WebService.NewController controller) { + public void define(WebService.NewController controller) { NewAction action = controller.createAction("list") .setDescription("List supported programming languages") .setSince("5.1") diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/authentication/ws/AuthenticationWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/authentication/ws/AuthenticationWsTest.java index 2e6612c685c..b7f3dc56118 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/authentication/ws/AuthenticationWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/authentication/ws/AuthenticationWsTest.java @@ -19,44 +19,36 @@ */ package org.sonar.server.authentication.ws; -import java.util.Arrays; +import java.util.Collections; import org.junit.Test; import org.sonar.api.server.ws.WebService; -import org.sonar.server.ws.ServletFilterHandler; -import org.sonar.server.ws.WsTester; import static org.assertj.core.api.Assertions.assertThat; public class AuthenticationWsTest { - - WsTester tester = new WsTester(new AuthenticationWs(Arrays.asList( - new LoginAction(null, null, null, null, null), - new LogoutAction(null, null), - new ValidateAction(null, null, null)))); + private AuthenticationWs underTest = new AuthenticationWs(Collections.singletonList(new AuthenticationWsAction() { + @Override + public void define(WebService.NewController controller) { + controller.createAction("foo") + .setHandler((request, response) -> { + throw new UnsupportedOperationException("not implemented"); + }); + } + })); @Test public void define_ws() { - WebService.Controller controller = tester.controller("api/authentication"); - assertThat(controller).isNotNull(); - assertThat(controller.description()).isNotEmpty(); - assertThat(controller.actions()).hasSize(3); + WebService.Context context = new WebService.Context(); - WebService.Action validate = controller.action("validate"); - assertThat(validate).isNotNull(); - assertThat(validate.handler()).isInstanceOf(ServletFilterHandler.class); - assertThat(validate.responseExampleAsString()).isNotEmpty(); - assertThat(validate.params()).isEmpty(); + underTest.define(context); - WebService.Action login = controller.action("login"); - assertThat(login).isNotNull(); - assertThat(login.handler()).isInstanceOf(ServletFilterHandler.class); - assertThat(login.isPost()).isTrue(); - assertThat(login.params()).hasSize(2); + WebService.Controller controller = context.controller("api/authentication"); + assertThat(controller).isNotNull(); + assertThat(controller.description()).isNotEmpty(); + assertThat(controller.actions()).hasSize(1); - WebService.Action logout = controller.action("logout"); - assertThat(logout).isNotNull(); - assertThat(logout.handler()).isInstanceOf(ServletFilterHandler.class); - assertThat(logout.isPost()).isTrue(); - assertThat(logout.params()).isEmpty(); + WebService.Action fooAction = controller.action("foo"); + assertThat(fooAction).isNotNull(); + assertThat(fooAction.handler()).isNotNull(); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/authentication/ws/LoginActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/authentication/ws/LoginActionTest.java index 05f5b9c0e71..4c77e88e5e2 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/authentication/ws/LoginActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/authentication/ws/LoginActionTest.java @@ -27,6 +27,7 @@ import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbSession; @@ -41,6 +42,7 @@ import org.sonar.server.authentication.event.AuthenticationException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.user.TestUserSessionFactory; import org.sonar.server.user.ThreadLocalUserSession; +import org.sonar.server.ws.ServletFilterHandler; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; @@ -85,6 +87,21 @@ public class LoginActionTest { dbSession.commit(); } + @Test + public void verify_definition() { + String controllerKey = "foo"; + WebService.Context context = new WebService.Context(); + WebService.NewController newController = context.createController(controllerKey); + underTest.define(newController); + newController.done(); + + WebService.Action login = context.controller(controllerKey).action("login"); + assertThat(login).isNotNull(); + assertThat(login.handler()).isInstanceOf(ServletFilterHandler.class); + assertThat(login.isPost()).isTrue(); + assertThat(login.params()).hasSize(2); + } + @Test public void do_get_pattern() { assertThat(underTest.doGetPattern().matches("/api/authentication/login")).isTrue(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/authentication/ws/LogoutActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/authentication/ws/LogoutActionTest.java index 0593331dbbe..9ad434f109f 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/authentication/ws/LogoutActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/authentication/ws/LogoutActionTest.java @@ -28,12 +28,14 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Rule; import org.junit.Test; +import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.user.UserDto; import org.sonar.server.authentication.JwtHttpHandler; import org.sonar.server.authentication.event.AuthenticationEvent; import org.sonar.server.authentication.event.AuthenticationException; +import org.sonar.server.ws.ServletFilterHandler; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; @@ -61,6 +63,21 @@ public class LogoutActionTest { private LogoutAction underTest = new LogoutAction(jwtHttpHandler, authenticationEvent); + @Test + public void verify_definition() { + String controllerKey = "foo"; + WebService.Context context = new WebService.Context(); + WebService.NewController newController = context.createController(controllerKey); + underTest.define(newController); + newController.done(); + + WebService.Action logout = context.controller(controllerKey).action("logout"); + assertThat(logout).isNotNull(); + assertThat(logout.handler()).isInstanceOf(ServletFilterHandler.class); + assertThat(logout.isPost()).isTrue(); + assertThat(logout.params()).isEmpty(); + } + @Test public void do_get_pattern() { assertThat(underTest.doGetPattern().matches("/api/authentication/logout")).isTrue(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/authentication/ws/ValidateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/authentication/ws/ValidateActionTest.java index 649818cbc64..a1d6dfe28c7 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/authentication/ws/ValidateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/authentication/ws/ValidateActionTest.java @@ -28,12 +28,15 @@ import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.sonar.api.config.internal.MapSettings; +import org.sonar.api.server.ws.WebService; import org.sonar.server.authentication.BasicAuthentication; import org.sonar.server.authentication.JwtHttpHandler; import org.sonar.server.authentication.event.AuthenticationException; +import org.sonar.server.ws.ServletFilterHandler; import org.sonar.test.JsonAssert; import org.sonarqube.ws.MediaTypes; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -61,6 +64,21 @@ public class ValidateActionTest { when(response.getWriter()).thenReturn(writer); } + @Test + public void verify_definition() { + String controllerKey = "foo"; + WebService.Context context = new WebService.Context(); + WebService.NewController newController = context.createController(controllerKey); + underTest.define(newController); + newController.done(); + + WebService.Action validate = context.controller(controllerKey).action("validate"); + assertThat(validate).isNotNull(); + assertThat(validate.handler()).isInstanceOf(ServletFilterHandler.class); + assertThat(validate.responseExampleAsString()).isNotEmpty(); + assertThat(validate.params()).isEmpty(); + } + @Test public void return_true_when_jwt_token_is_set() throws Exception { when(jwtHttpHandler.validateToken(request, response)).thenReturn(Optional.of(newUserDto())); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/favorite/ws/FavoritesWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/favorite/ws/FavoritesWsTest.java index 474cc50f8bb..2a35bc5e77b 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/favorite/ws/FavoritesWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/favorite/ws/FavoritesWsTest.java @@ -20,25 +20,33 @@ package org.sonar.server.favorite.ws; import org.junit.Test; -import org.sonar.api.server.ws.WebService.Controller; -import org.sonar.db.DbClient; -import org.sonar.server.component.ComponentFinder; -import org.sonar.server.favorite.FavoriteUpdater; -import org.sonar.server.user.UserSession; -import org.sonar.server.ws.WsTester; +import org.sonar.api.server.ws.Request; +import org.sonar.api.server.ws.Response; +import org.sonar.api.server.ws.WebService; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; public class FavoritesWsTest { - private final FavoritesWsAction[] actions = {new AddAction(mock(UserSession.class), mock(DbClient.class), mock(FavoriteUpdater.class), mock(ComponentFinder.class))}; - private WsTester ws = new WsTester(new FavoritesWs(actions)); + private final FavoritesWsAction[] actions = {new FavoritesWsAction() { + @Override + public void define(WebService.NewController context) { + context.createAction("foo").setHandler(this); + } - private Controller underTest = ws.controller("api/favorites"); + @Override + public void handle(Request request, Response response) { + + } + }}; + private FavoritesWs underTest = new FavoritesWs(actions); @Test public void definition() { - assertThat(underTest.path()).isEqualTo("api/favorites"); + WebService.Context context = new WebService.Context(); + + underTest.define(context); + + assertThat(context.controller("api/favorites")).isNotNull(); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/language/ws/LanguageWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/language/ws/LanguageWsTest.java index 23139cfffa9..5a365578124 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/language/ws/LanguageWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/language/ws/LanguageWsTest.java @@ -19,47 +19,27 @@ */ package org.sonar.server.language.ws; -import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; -import org.sonar.api.resources.AbstractLanguage; -import org.sonar.api.resources.Language; -import org.sonar.api.resources.Languages; +import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Action; import org.sonar.api.server.ws.WebService.Controller; -import org.sonar.server.ws.WsTester; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(MockitoJUnitRunner.class) public class LanguageWsTest { private static final String CONTROLLER_LANGUAGES = "api/languages"; private static final String ACTION_LIST = "list"; - private static final String EMPTY_JSON_RESPONSE = "{\"languages\": []}"; - @Mock - private Languages languages; - - private WsTester tester; - - @Before - public void setUp() { - Mockito.when(languages.all()).thenReturn(new Language[] { - new Ook(), - new LolCode(), - new Whitespace(), - new ArnoldC() - }); - tester = new WsTester(new LanguageWs(new ListAction(languages))); - } + private LanguageWs underTest = new LanguageWs(new ListAction(null)); @Test public void should_be_well_defined() { - Controller controller = tester.controller(CONTROLLER_LANGUAGES); + WebService.Context context = new WebService.Context(); + + underTest.define(context); + + Controller controller = context.controller(CONTROLLER_LANGUAGES); assertThat(controller).isNotNull(); assertThat(controller.description()).isNotEmpty(); assertThat(controller.isInternal()).isFalse(); @@ -76,81 +56,4 @@ public class LanguageWsTest { assertThat(list.responseExampleAsString()).isNotEmpty(); assertThat(list.params()).hasSize(2); } - - @Test - public void list_all_languages() throws Exception { - tester.newGetRequest(CONTROLLER_LANGUAGES, ACTION_LIST).execute().assertJson(this.getClass(), "list.json"); - - tester.newGetRequest(CONTROLLER_LANGUAGES, ACTION_LIST) - .setParam("ps", "2") - .execute().assertJson(this.getClass(), "list_limited.json"); - tester.newGetRequest(CONTROLLER_LANGUAGES, ACTION_LIST) - .setParam("ps", "4") - .execute().assertJson(this.getClass(), "list.json"); - tester.newGetRequest(CONTROLLER_LANGUAGES, ACTION_LIST) - .setParam("ps", "10") - .execute().assertJson(this.getClass(), "list.json"); - } - - @Test - public void filter_languages_by_key_or_name() throws Exception { - tester.newGetRequest(CONTROLLER_LANGUAGES, ACTION_LIST) - .setParam("q", "ws") - .execute().assertJson(this.getClass(), "list_filtered_key.json"); - tester.newGetRequest(CONTROLLER_LANGUAGES, ACTION_LIST) - .setParam("q", "o") - .execute().assertJson(this.getClass(), "list_filtered_name.json"); - } - - /** - * Potential vulnerability : the query provided by user must - * not be executed as a regexp. - */ - @Test - public void filter_escapes_the_user_query() throws Exception { - // invalid regexp - tester.newGetRequest(CONTROLLER_LANGUAGES, ACTION_LIST) - .setParam("q", "[") - .execute().assertJson(EMPTY_JSON_RESPONSE); - - // do not consider param as a regexp - tester.newGetRequest(CONTROLLER_LANGUAGES, ACTION_LIST) - .setParam("q", ".*") - .execute().assertJson(EMPTY_JSON_RESPONSE); - } - - static abstract class TestLanguage extends AbstractLanguage { - TestLanguage(String key, String language) { - super(key, language); - } - - @Override - public String[] getFileSuffixes() { - return new String[0]; - } - } - - static class Ook extends TestLanguage { - public Ook() { - super("ook", "Ook!"); - } - } - - static class LolCode extends TestLanguage { - public LolCode() { - super("lol", "LOLCODE"); - } - } - - static class Whitespace extends TestLanguage { - public Whitespace() { - super("ws", "Whitespace"); - } - } - - static class ArnoldC extends TestLanguage { - public ArnoldC() { - super("ac", "ArnoldC"); - } - } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/language/ws/ListActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/language/ws/ListActionTest.java new file mode 100644 index 00000000000..bbc397fe916 --- /dev/null +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/language/ws/ListActionTest.java @@ -0,0 +1,125 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.server.language.ws; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.sonar.api.resources.AbstractLanguage; +import org.sonar.api.resources.Language; +import org.sonar.api.resources.Languages; +import org.sonar.server.ws.WsActionTester; + +import static org.mockito.Mockito.mock; + +public class ListActionTest { + private static final String EMPTY_JSON_RESPONSE = "{\"languages\": []}"; + + private Languages languages = mock(Languages.class); + private ListAction underTest = new ListAction(languages); + private WsActionTester tester = new WsActionTester(underTest); + + @Before + public void setUp() { + Mockito.when(languages.all()).thenReturn(new Language[] { + new Ook(), + new LolCode(), + new Whitespace(), + new ArnoldC() + }); + } + + @Test + public void list_all_languages() { + tester.newRequest().execute().assertJson(this.getClass(), "list.json"); + + tester.newRequest() + .setParam("ps", "2") + .execute().assertJson(this.getClass(), "list_limited.json"); + tester.newRequest() + .setParam("ps", "4") + .execute().assertJson(this.getClass(), "list.json"); + tester.newRequest() + .setParam("ps", "10") + .execute().assertJson(this.getClass(), "list.json"); + } + + @Test + public void filter_languages_by_key_or_name() { + tester.newRequest() + .setParam("q", "ws") + .execute().assertJson(this.getClass(), "list_filtered_key.json"); + tester.newRequest() + .setParam("q", "o") + .execute().assertJson(this.getClass(), "list_filtered_name.json"); + } + + /** + * Potential vulnerability : the query provided by user must + * not be executed as a regexp. + */ + @Test + public void filter_escapes_the_user_query() { + // invalid regexp + tester.newRequest() + .setParam("q", "[") + .execute().assertJson(EMPTY_JSON_RESPONSE); + + // do not consider param as a regexp + tester.newRequest() + .setParam("q", ".*") + .execute().assertJson(EMPTY_JSON_RESPONSE); + } + + static abstract class TestLanguage extends AbstractLanguage { + TestLanguage(String key, String language) { + super(key, language); + } + + @Override + public String[] getFileSuffixes() { + return new String[0]; + } + } + + static class Ook extends TestLanguage { + Ook() { + super("ook", "Ook!"); + } + } + + static class LolCode extends TestLanguage { + LolCode() { + super("lol", "LOLCODE"); + } + } + + static class Whitespace extends TestLanguage { + Whitespace() { + super("ws", "Whitespace"); + } + } + + static class ArnoldC extends TestLanguage { + ArnoldC() { + super("ac", "ArnoldC"); + } + } +} diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/custom/ws/CustomMeasuresWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/custom/ws/CustomMeasuresWsTest.java index 746ba88a4d3..d07d6c655f8 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/custom/ws/CustomMeasuresWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/custom/ws/CustomMeasuresWsTest.java @@ -19,56 +19,36 @@ */ package org.sonar.server.measure.custom.ws; -import org.junit.Before; import org.junit.Test; +import org.sonar.api.server.ws.Request; +import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; -import org.sonar.api.utils.System2; -import org.sonar.db.DbClient; -import org.sonar.server.component.ComponentFinder; -import org.sonar.server.user.UserSession; -import org.sonar.server.ws.WsTester; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.sonar.server.measure.custom.ws.CustomMeasuresWs.ENDPOINT; public class CustomMeasuresWsTest { - WsTester ws; + private CustomMeasuresWs underTest = new CustomMeasuresWs(new CustomMeasuresWsAction() { + @Override + public void define(WebService.NewController context) { + context.createAction("foo").setHandler(this); + } - @Before - public void setUp() { - DbClient dbClient = mock(DbClient.class); - UserSession userSession = mock(UserSession.class); - ws = new WsTester(new CustomMeasuresWs( - new DeleteAction(dbClient, userSession), - new CreateAction(dbClient, userSession, System2.INSTANCE, mock(CustomMeasureValidator.class), mock(CustomMeasureJsonWriter.class), mock(ComponentFinder.class)), - new UpdateAction(dbClient, userSession, System2.INSTANCE, mock(CustomMeasureValidator.class), mock(CustomMeasureJsonWriter.class)) - )); - } + @Override + public void handle(Request request, Response response) { + + } + }); @Test public void define_ws() { - WebService.Controller controller = ws.controller("api/custom_measures"); - assertThat(controller).isNotNull(); - assertThat(controller.description()).isNotEmpty(); - assertThat(controller.actions()).hasSize(3); - } + WebService.Context context = new WebService.Context(); - @Test - public void delete_action_properties() { - WebService.Action deleteAction = ws.controller(ENDPOINT).action("delete"); - assertThat(deleteAction.isPost()).isTrue(); - } + underTest.define(context); - @Test - public void create_action_properties() { - WebService.Action action = ws.controller(ENDPOINT).action("create"); - assertThat(action.isPost()).isTrue(); + WebService.Controller controller = context.controller("api/custom_measures"); + assertThat(controller).isNotNull(); + assertThat(controller.description()).isNotEmpty(); + assertThat(controller.actions()).hasSize(1); } - @Test - public void create_update_properties() { - WebService.Action action = ws.controller(ENDPOINT).action("update"); - assertThat(action.isPost()).isTrue(); - } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/custom/ws/DeleteActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/custom/ws/DeleteActionTest.java index 0c50b9147d4..43f3afdbb0a 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/custom/ws/DeleteActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/custom/ws/DeleteActionTest.java @@ -19,7 +19,6 @@ */ package org.sonar.server.measure.custom.ws; -import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -33,7 +32,7 @@ import org.sonar.db.measure.custom.CustomMeasureDto; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.ws.WsTester; +import org.sonar.server.ws.WsActionTester; import static java.lang.String.valueOf; import static org.assertj.core.api.Assertions.assertThat; @@ -42,8 +41,6 @@ import static org.sonar.server.measure.custom.ws.DeleteAction.PARAM_ID; public class DeleteActionTest { - public static final String ACTION = "delete"; - @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -53,50 +50,46 @@ public class DeleteActionTest { private DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); - private WsTester ws; - - @Before - public void setUp() { - ws = new WsTester(new CustomMeasuresWs(new DeleteAction(dbClient, userSession))); - } + private DeleteAction underTest = new DeleteAction(dbClient, userSession); + private WsActionTester tester = new WsActionTester(underTest); @Test - public void project_administrator_can_delete_custom_measures() throws Exception { + public void project_administrator_can_delete_custom_measures() { ComponentDto project = db.components().insertPrivateProject(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); long id = insertCustomMeasure(project); - newRequest().setParam(PARAM_ID, valueOf(id)).execute(); + tester.newRequest().setParam(PARAM_ID, valueOf(id)).execute(); assertThat(dbClient.customMeasureDao().selectById(dbSession, id)).isNull(); } @Test - public void throw_RowNotFoundException_if_id_does_not_exist() throws Exception { + public void throw_RowNotFoundException_if_id_does_not_exist() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Custom measure with id '42' does not exist"); - newRequest().setParam(PARAM_ID, "42").execute(); + tester.newRequest().setParam(PARAM_ID, "42").execute(); } @Test - public void throw_ForbiddenException_if_not_system_administrator() throws Exception { + public void throw_ForbiddenException_if_not_system_administrator() { ComponentDto project = db.components().insertPrivateProject(); long id = insertCustomMeasure(project); userSession.logIn().setNonSystemAdministrator(); expectedException.expect(ForbiddenException.class); - newRequest().setParam(PARAM_ID, valueOf(id)).execute(); + tester.newRequest().setParam(PARAM_ID, valueOf(id)).execute(); } @Test - public void throw_UnauthorizedException_if_not_logged_in() throws Exception { + public void throw_UnauthorizedException_if_not_logged_in() { ComponentDto project = db.components().insertPrivateProject(); long id = insertCustomMeasure(project); userSession.anonymous(); expectedException.expect(UnauthorizedException.class); - newRequest().setParam(PARAM_ID, valueOf(id)).execute(); + tester.newRequest().setParam(PARAM_ID, valueOf(id)).execute(); } private long insertCustomMeasure(ComponentDto component) { @@ -106,7 +99,4 @@ public class DeleteActionTest { return dto.getId(); } - private WsTester.TestRequest newRequest() { - return ws.newPostRequest(CustomMeasuresWs.ENDPOINT, ACTION); - } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/custom/ws/MetricsActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/custom/ws/MetricsActionTest.java index bd458853ec0..089552f1433 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/custom/ws/MetricsActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/custom/ws/MetricsActionTest.java @@ -37,13 +37,12 @@ import org.sonar.server.component.TestComponentFinder; import org.sonar.server.es.EsTester; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.ws.WsTester; +import org.sonar.server.ws.TestResponse; +import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.db.measure.custom.CustomMeasureTesting.newCustomMeasureDto; import static org.sonar.db.metric.MetricTesting.newMetricDto; -import static org.sonar.server.measure.custom.ws.CustomMeasuresWs.ENDPOINT; -import static org.sonar.server.measure.custom.ws.MetricsAction.ACTION; public class MetricsActionTest { private static final String DEFAULT_PROJECT_UUID = "project-uuid"; @@ -61,34 +60,34 @@ public class MetricsActionTest { private final DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); private ComponentDto defaultProject; - private WsTester ws; + private MetricsAction underTest = new MetricsAction(dbClient, userSession, TestComponentFinder.from(db)); + private WsActionTester tester = new WsActionTester(underTest); @Before public void setUp() throws Exception { defaultProject = insertDefaultProject(); userSession.logIn().addProjectPermission(UserRole.ADMIN, defaultProject); - ws = new WsTester(new CustomMeasuresWs(new MetricsAction(dbClient, userSession, TestComponentFinder.from(db)))); } @Test - public void list_metrics() throws Exception { + public void list_metrics() { insertCustomMetric("metric-key-1"); insertCustomMetric("metric-key-2"); insertCustomMetric("metric-key-3"); - String response = newRequest().outputAsString(); + String response = newRequest().getInput(); assertThat(response).contains("metric-key-1", "metric-key-2", "metric-key-3"); } @Test - public void list_metrics_active_and_custom_only() throws Exception { + public void list_metrics_active_and_custom_only() { insertCustomMetric("metric-key-1"); dbClient.metricDao().insert(dbSession, newMetricDto().setEnabled(true).setUserManaged(false).setKey("metric-key-2")); dbClient.metricDao().insert(dbSession, newMetricDto().setEnabled(false).setUserManaged(true).setKey("metric-key-3")); dbSession.commit(); - String response = newRequest().outputAsString(); + String response = newRequest().getInput(); assertThat(response).contains("metric-key-1") .doesNotContain("metric-key-2") @@ -96,7 +95,7 @@ public class MetricsActionTest { } @Test - public void list_metrics_where_no_existing_custom_measure() throws Exception { + public void list_metrics_where_no_existing_custom_measure() { MetricDto metric = insertCustomMetric("metric-key-1"); insertCustomMetric("metric-key-2"); insertProject("project-uuid-2", "project-key-2"); @@ -107,14 +106,14 @@ public class MetricsActionTest { dbClient.customMeasureDao().insert(dbSession, customMeasure); dbSession.commit(); - String response = newRequest().outputAsString(); + String response = newRequest().getInput(); assertThat(response).contains("metric-key-2") .doesNotContain("metric-key-1"); } @Test - public void list_metrics_based_on_project_key() throws Exception { + public void list_metrics_based_on_project_key() { MetricDto metric = insertCustomMetric("metric-key-1"); insertCustomMetric("metric-key-2"); insertProject("project-uuid-2", "project-key-2"); @@ -125,26 +124,26 @@ public class MetricsActionTest { dbClient.customMeasureDao().insert(dbSession, customMeasure); dbSession.commit(); - String response = ws.newGetRequest(ENDPOINT, ACTION) + String response = tester.newRequest() .setParam(MetricsAction.PARAM_PROJECT_KEY, DEFAULT_PROJECT_KEY) - .execute().outputAsString(); + .execute().getInput(); assertThat(response).contains("metric-key-2") .doesNotContain("metric-key-1"); } @Test - public void list_metrics_as_a_project_admin() throws Exception { + public void list_metrics_as_a_project_admin() { insertCustomMetric("metric-key-1"); userSession.logIn("login").addProjectPermission(UserRole.ADMIN, defaultProject); - String response = newRequest().outputAsString(); + String response = newRequest().getInput(); assertThat(response).contains("metric-key-1"); } @Test - public void response_with_correct_formatting() throws Exception { + public void response_with_correct_formatting() { dbClient.metricDao().insert(dbSession, newCustomMetric("custom-key-1") .setShortName("custom-name-1") .setDescription("custom-description-1") @@ -171,7 +170,7 @@ public class MetricsActionTest { .setHidden(false)); dbSession.commit(); - WsTester.Result response = ws.newGetRequest(ENDPOINT, ACTION) + TestResponse response = tester.newRequest() .setParam(MetricsAction.PARAM_PROJECT_ID, DEFAULT_PROJECT_UUID) .execute(); @@ -179,14 +178,14 @@ public class MetricsActionTest { } @Test - public void fail_if_project_id_nor_project_key_provided() throws Exception { + public void fail_if_project_id_nor_project_key_provided() { expectedException.expect(IllegalArgumentException.class); - ws.newGetRequest(ENDPOINT, ACTION).execute(); + tester.newRequest().execute(); } @Test - public void fail_if_insufficient_privilege() throws Exception { + public void fail_if_insufficient_privilege() { expectedException.expect(ForbiddenException.class); userSession.logIn("login"); @@ -195,8 +194,8 @@ public class MetricsActionTest { newRequest(); } - private WsTester.Result newRequest() throws Exception { - return ws.newGetRequest(ENDPOINT, ACTION) + private TestResponse newRequest() { + return tester.newRequest() .setParam(MetricsAction.PARAM_PROJECT_ID, DEFAULT_PROJECT_UUID) .execute(); } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/MeasuresWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/MeasuresWsTest.java index 81e2ba59d65..52f7a37a636 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/MeasuresWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/MeasuresWsTest.java @@ -21,19 +21,19 @@ package org.sonar.server.measure.ws; import org.junit.Test; import org.sonar.api.server.ws.WebService; -import org.sonar.server.ws.WsTester; import static org.assertj.core.api.Assertions.assertThat; public class MeasuresWsTest { - WsTester ws = new WsTester( - new MeasuresWs( - new ComponentAction(null, null, null))); + private MeasuresWs underTest = new MeasuresWs(new ComponentAction(null, null, null)); @Test public void define_ws() { - WebService.Controller controller = ws.controller("api/measures"); + WebService.Context context = new WebService.Context(); + underTest.define(context); + + WebService.Controller controller = context.controller("api/measures"); assertThat(controller).isNotNull(); assertThat(controller.since()).isEqualTo("5.4"); } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/TimeMachineWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/TimeMachineWsTest.java index 58350cca5a3..4696ff29293 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/TimeMachineWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/TimeMachineWsTest.java @@ -19,25 +19,23 @@ */ package org.sonar.server.measure.ws; -import org.junit.Before; import org.junit.Test; import org.sonar.api.server.ws.WebService; -import org.sonar.server.ws.WsTester; import static org.assertj.core.api.Assertions.assertThat; public class TimeMachineWsTest { - WebService.Controller controller; - - @Before - public void setUp() { - WsTester tester = new WsTester(new TimeMachineWs()); - controller = tester.controller("api/timemachine"); - } + private TimeMachineWs underTest = new TimeMachineWs(); @Test public void define_controller() { + WebService.Context context = new WebService.Context(); + + underTest.define(context); + + WebService.Controller controller = context.controller("api/timemachine"); + assertThat(controller).isNotNull(); assertThat(controller.since()).isEqualTo("2.10"); assertThat(controller.description()).isNotEmpty(); @@ -46,6 +44,11 @@ public class TimeMachineWsTest { @Test public void define_index_action() { + WebService.Context context = new WebService.Context(); + + underTest.define(context); + + WebService.Controller controller = context.controller("api/timemachine"); WebService.Action action = controller.action("index"); assertThat(action).isNotNull(); assertThat(action.responseExampleAsString()).isNotEmpty(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/CreateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/CreateActionTest.java index 5fa395b746b..8c76d1e72f8 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/CreateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/CreateActionTest.java @@ -35,7 +35,8 @@ import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.ServerException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.ws.WsTester; +import org.sonar.server.ws.TestResponse; +import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.server.metric.ws.CreateAction.PARAM_DESCRIPTION; @@ -61,17 +62,17 @@ public class CreateActionTest { private DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); - private WsTester ws; + private CreateAction underTest = new CreateAction(dbClient, userSessionRule); + private WsActionTester tester = new WsActionTester(underTest); @Before public void setUp() { - ws = new WsTester(new MetricsWs(new CreateAction(dbClient, userSessionRule))); userSessionRule.logIn().setSystemAdministrator(); } @Test - public void insert_new_minimalist_metric() throws Exception { - newRequest() + public void insert_new_minimalist_metric() { + tester.newRequest() .setParam(PARAM_KEY, DEFAULT_KEY) .setParam(PARAM_NAME, DEFAULT_NAME) .setParam(PARAM_TYPE, DEFAULT_TYPE) @@ -91,8 +92,8 @@ public class CreateActionTest { } @Test - public void insert_new_full_metric() throws Exception { - newRequest() + public void insert_new_full_metric() { + tester.newRequest() .setParam(PARAM_KEY, DEFAULT_KEY) .setParam(PARAM_NAME, DEFAULT_NAME) .setParam(PARAM_TYPE, DEFAULT_TYPE) @@ -108,8 +109,8 @@ public class CreateActionTest { } @Test - public void return_metric_with_id() throws Exception { - WsTester.Result result = newRequest() + public void return_metric_with_id() { + TestResponse result = tester.newRequest() .setParam(PARAM_KEY, DEFAULT_KEY) .setParam(PARAM_NAME, DEFAULT_NAME) .setParam(PARAM_TYPE, DEFAULT_TYPE) @@ -118,11 +119,11 @@ public class CreateActionTest { .execute(); result.assertJson(getClass(), "metric.json"); - assertThat(result.outputAsString()).matches(".*\"id\"\\s*:\\s*\"\\w+\".*"); + assertThat(result.getInput()).matches(".*\"id\"\\s*:\\s*\"\\w+\".*"); } @Test - public void update_existing_metric_when_custom_and_disabled() throws Exception { + public void update_existing_metric_when_custom_and_disabled() { MetricDto metricInDb = MetricTesting.newMetricDto() .setKey(DEFAULT_KEY) .setValueType(ValueType.BOOL.name()) @@ -131,7 +132,7 @@ public class CreateActionTest { dbClient.metricDao().insert(dbSession, metricInDb); dbSession.commit(); - WsTester.Result result = newRequest() + TestResponse result = tester.newRequest() .setParam(PARAM_KEY, DEFAULT_KEY) .setParam(PARAM_NAME, DEFAULT_NAME) .setParam(PARAM_TYPE, DEFAULT_TYPE) @@ -140,7 +141,7 @@ public class CreateActionTest { .execute(); result.assertJson(getClass(), "metric.json"); - result.outputAsString().matches("\"id\"\\s*:\\s*\"" + metricInDb.getId() + "\""); + result.getInput().matches("\"id\"\\s*:\\s*\"" + metricInDb.getId() + "\""); MetricDto metricAfterWs = dbClient.metricDao().selectByKey(dbSession, DEFAULT_KEY); assertThat(metricAfterWs.getId()).isEqualTo(metricInDb.getId()); assertThat(metricAfterWs.getDomain()).isEqualTo(DEFAULT_DOMAIN); @@ -150,7 +151,7 @@ public class CreateActionTest { } @Test - public void fail_when_existing_activated_metric_with_same_key() throws Exception { + public void fail_when_existing_activated_metric_with_same_key() { expectedException.expect(ServerException.class); dbClient.metricDao().insert(dbSession, MetricTesting.newMetricDto() .setKey(DEFAULT_KEY) @@ -159,14 +160,14 @@ public class CreateActionTest { .setEnabled(true)); dbSession.commit(); - newRequest() + tester.newRequest() .setParam(PARAM_KEY, DEFAULT_KEY) .setParam(PARAM_NAME, "any-name") .setParam(PARAM_TYPE, DEFAULT_TYPE).execute(); } @Test - public void fail_when_existing_non_custom_metric_with_same_key() throws Exception { + public void fail_when_existing_non_custom_metric_with_same_key() { expectedException.expect(ServerException.class); dbClient.metricDao().insert(dbSession, MetricTesting.newMetricDto() .setKey(DEFAULT_KEY) @@ -175,14 +176,14 @@ public class CreateActionTest { .setEnabled(false)); dbSession.commit(); - newRequest() + tester.newRequest() .setParam(PARAM_KEY, DEFAULT_KEY) .setParam(PARAM_NAME, "any-name") .setParam(PARAM_TYPE, DEFAULT_TYPE).execute(); } @Test - public void fail_when_metric_type_is_changed_and_associated_measures_exist() throws Exception { + public void fail_when_metric_type_is_changed_and_associated_measures_exist() { expectedException.expect(ServerException.class); MetricDto metric = MetricTesting.newMetricDto() .setKey(DEFAULT_KEY) @@ -193,7 +194,7 @@ public class CreateActionTest { dbClient.customMeasureDao().insert(dbSession, CustomMeasureTesting.newCustomMeasureDto().setMetricId(metric.getId())); dbSession.commit(); - newRequest() + tester.newRequest() .setParam(PARAM_KEY, DEFAULT_KEY) .setParam(PARAM_NAME, "any-name") .setParam(PARAM_TYPE, ValueType.INT.name()) @@ -201,40 +202,40 @@ public class CreateActionTest { } @Test - public void fail_when_missing_key() throws Exception { + public void fail_when_missing_key() { expectedException.expect(IllegalArgumentException.class); - newRequest() + tester.newRequest() .setParam(PARAM_NAME, DEFAULT_NAME) .setParam(PARAM_TYPE, DEFAULT_TYPE).execute(); } @Test - public void fail_when_missing_name() throws Exception { + public void fail_when_missing_name() { expectedException.expect(IllegalArgumentException.class); - newRequest() + tester.newRequest() .setParam(PARAM_KEY, DEFAULT_KEY) .setParam(PARAM_TYPE, DEFAULT_TYPE).execute(); } @Test - public void fail_when_missing_type() throws Exception { + public void fail_when_missing_type() { expectedException.expect(IllegalArgumentException.class); - newRequest() + tester.newRequest() .setParam(PARAM_NAME, DEFAULT_NAME) .setParam(PARAM_KEY, DEFAULT_KEY).execute(); } @Test - public void throw_ForbiddenException_if_not_system_administrator() throws Exception { + public void throw_ForbiddenException_if_not_system_administrator() { userSessionRule.logIn().setNonSystemAdministrator(); expectedException.expect(ForbiddenException.class); expectedException.expectMessage("Insufficient privileges"); - newRequest() + tester.newRequest() .setParam(PARAM_KEY, "any-key") .setParam(PARAM_NAME, "any-name") .setParam(PARAM_TYPE, DEFAULT_TYPE) @@ -242,13 +243,13 @@ public class CreateActionTest { } @Test - public void throw_UnauthorizedException_if_not_logged_in() throws Exception { + public void throw_UnauthorizedException_if_not_logged_in() { userSessionRule.anonymous(); expectedException.expect(UnauthorizedException.class); expectedException.expectMessage("Authentication is required"); - newRequest() + tester.newRequest() .setParam(PARAM_KEY, "any-key") .setParam(PARAM_NAME, "any-name") .setParam(PARAM_TYPE, DEFAULT_TYPE) @@ -256,11 +257,11 @@ public class CreateActionTest { } @Test - public void fail_when_ill_formatted_key() throws Exception { + public void fail_when_ill_formatted_key() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Malformed metric key '123:456'. Allowed characters are alphanumeric, '-', '_', with at least one non-digit."); - newRequest() + tester.newRequest() .setParam(PARAM_KEY, "123:456") .setParam(PARAM_NAME, DEFAULT_NAME) .setParam(PARAM_TYPE, DEFAULT_TYPE) @@ -268,10 +269,10 @@ public class CreateActionTest { } @Test - public void fail_when_empty_name() throws Exception { + public void fail_when_empty_name() { expectedException.expect(IllegalArgumentException.class); - newRequest() + tester.newRequest() .setParam(PARAM_KEY, DEFAULT_KEY) .setParam(PARAM_NAME, "") .setParam(PARAM_TYPE, DEFAULT_TYPE) @@ -279,17 +280,14 @@ public class CreateActionTest { } @Test - public void fail_when_empty_type() throws Exception { + public void fail_when_empty_type() { expectedException.expect(IllegalArgumentException.class); - newRequest() + tester.newRequest() .setParam(PARAM_KEY, DEFAULT_KEY) .setParam(PARAM_NAME, DEFAULT_NAME) .setParam(PARAM_TYPE, "") .execute(); } - private WsTester.TestRequest newRequest() { - return ws.newPostRequest("api/metrics", "create"); - } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/DomainsActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/DomainsActionTest.java index 9ba13fa2031..d43e868efaa 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/DomainsActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/DomainsActionTest.java @@ -20,7 +20,6 @@ package org.sonar.server.metric.ws; import org.junit.After; -import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.System2; @@ -30,7 +29,8 @@ import org.sonar.db.DbTester; import org.sonar.db.TestDBSessions; import org.sonar.db.metric.MetricDao; import org.sonar.db.metric.MetricDto; -import org.sonar.server.ws.WsTester; +import org.sonar.server.ws.TestRequest; +import org.sonar.server.ws.WsActionTester; import org.sonar.test.JsonAssert; import static org.sonar.db.metric.MetricTesting.newMetricDto; @@ -40,16 +40,11 @@ public class DomainsActionTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); - WsTester ws; - DbClient dbClient; - DbSession dbSession; - @Before - public void setUp() { - dbClient = new DbClient(db.database(), db.myBatis(), new TestDBSessions(db.myBatis()), new MetricDao()); - dbSession = dbClient.openSession(false); - ws = new WsTester(new MetricsWs(new DomainsAction(dbClient))); - } + private DbClient dbClient = new DbClient(db.database(), db.myBatis(), new TestDBSessions(db.myBatis()), new MetricDao()); + private DbSession dbSession = dbClient.openSession(false); + private DomainsAction underTest = new DomainsAction(dbClient); + private WsActionTester tester = new WsActionTester(underTest); @After public void tearDown() { @@ -57,7 +52,7 @@ public class DomainsActionTest { } @Test - public void json_example_validated() throws Exception { + public void json_example_validated() { insertNewMetricDto(newEnabledMetric("API Compatibility")); insertNewMetricDto(newEnabledMetric("Issues")); insertNewMetricDto(newEnabledMetric("Rules")); @@ -67,9 +62,9 @@ public class DomainsActionTest { insertNewMetricDto(newEnabledMetric("")); insertNewMetricDto(newMetricDto().setDomain("Domain of Deactivated Metric").setEnabled(false)); - WsTester.Result result = ws.newGetRequest(MetricsWs.ENDPOINT, "domains").execute(); + TestRequest result = tester.newRequest(); - JsonAssert.assertJson(result.outputAsString()).isSimilarTo(getClass().getResource("example-domains.json")); + JsonAssert.assertJson(result.execute().getInput()).isSimilarTo(getClass().getResource("example-domains.json")); } private void insertNewMetricDto(MetricDto metric) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/MetricsWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/MetricsWsTest.java index 5e5bd69af64..73ab79676c7 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/MetricsWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/MetricsWsTest.java @@ -19,36 +19,33 @@ */ package org.sonar.server.metric.ws; -import org.junit.Before; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.server.user.UserSession; -import org.sonar.server.ws.WsTester; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class MetricsWsTest { - WsTester ws; - - @Before - public void setUp() { - DbClient dbClient = mock(DbClient.class); - UserSession userSession = mock(UserSession.class); - ws = new WsTester(new MetricsWs( + private DbClient dbClient = mock(DbClient.class); + private UserSession userSession = mock(UserSession.class); + private MetricsWs underTest = new MetricsWs( new SearchAction(dbClient), new CreateAction(dbClient, userSession), new UpdateAction(dbClient, userSession), new DeleteAction(dbClient, userSession), new TypesAction(), - new DomainsAction(dbClient))); - } + new DomainsAction(dbClient)); @Test public void define_ws() { - WebService.Controller controller = ws.controller("api/metrics"); + WebService.Context context = new WebService.Context(); + + underTest.define(context); + + WebService.Controller controller = context.controller("api/metrics"); assertThat(controller).isNotNull(); assertThat(controller.description()).isNotEmpty(); assertThat(controller.actions()).hasSize(6); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/SearchActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/SearchActionTest.java index ac22e97a59b..ccb00bae49a 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/SearchActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/SearchActionTest.java @@ -20,7 +20,6 @@ package org.sonar.server.metric.ws; import org.apache.commons.lang.StringUtils; -import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService.Param; @@ -29,42 +28,39 @@ import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.metric.MetricDto; -import org.sonar.server.ws.WsTester; +import org.sonar.server.ws.TestResponse; +import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.db.metric.MetricTesting.newMetricDto; import static org.sonar.server.metric.ws.SearchAction.PARAM_IS_CUSTOM; - public class SearchActionTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); - DbClient dbClient = db.getDbClient(); - final DbSession dbSession = db.getSession(); - WsTester ws; - @Before - public void setUp() { - ws = new WsTester(new MetricsWs(new SearchAction(dbClient))); - } + private DbClient dbClient = db.getDbClient(); + private final DbSession dbSession = db.getSession(); + private SearchAction underTest = new SearchAction(dbClient); + private WsActionTester tester = new WsActionTester(underTest); @Test - public void search_metrics_in_database() throws Exception { + public void search_metrics_in_database() { insertNewCustomMetric("1", "2", "3"); - WsTester.Result result = newRequest().execute(); + TestResponse result = tester.newRequest().execute(); result.assertJson(getClass(), "search_metrics.json"); } @Test - public void search_metrics_ordered_by_name_case_insensitive() throws Exception { + public void search_metrics_ordered_by_name_case_insensitive() { insertNewCustomMetric("3", "1", "2"); - String firstResult = newRequest().setParam(Param.PAGE, "1").setParam(Param.PAGE_SIZE, "1").execute().outputAsString(); - String secondResult = newRequest().setParam(Param.PAGE, "2").setParam(Param.PAGE_SIZE, "1").execute().outputAsString(); - String thirdResult = newRequest().setParam(Param.PAGE, "3").setParam(Param.PAGE_SIZE, "1").execute().outputAsString(); + String firstResult = tester.newRequest().setParam(Param.PAGE, "1").setParam(Param.PAGE_SIZE, "1").execute().getInput(); + String secondResult = tester.newRequest().setParam(Param.PAGE, "2").setParam(Param.PAGE_SIZE, "1").execute().getInput(); + String thirdResult = tester.newRequest().setParam(Param.PAGE, "3").setParam(Param.PAGE_SIZE, "1").execute().getInput(); assertThat(firstResult).contains("custom-key-1").doesNotContain("custom-key-2").doesNotContain("custom-key-3"); assertThat(secondResult).contains("custom-key-2").doesNotContain("custom-key-1").doesNotContain("custom-key-3"); @@ -72,36 +68,36 @@ public class SearchActionTest { } @Test - public void search_metrics_with_pagination() throws Exception { + public void search_metrics_with_pagination() { insertNewCustomMetric("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"); - WsTester.Result result = newRequest() + TestResponse result = tester.newRequest() .setParam(Param.PAGE, "3") .setParam(Param.PAGE_SIZE, "4") .execute(); - assertThat(StringUtils.countMatches(result.outputAsString(), "custom-key")).isEqualTo(2); + assertThat(StringUtils.countMatches(result.getInput(), "custom-key")).isEqualTo(2); } @Test - public void list_metric_with_is_custom_true() throws Exception { + public void list_metric_with_is_custom_true() { insertNewCustomMetric("1", "2"); insertNewNonCustomMetric("3"); - String result = newRequest() - .setParam(PARAM_IS_CUSTOM, "true").execute().outputAsString(); + String result = tester.newRequest() + .setParam(PARAM_IS_CUSTOM, "true").execute().getInput(); assertThat(result).contains("custom-key-1", "custom-key-2") .doesNotContain("non-custom-key-3"); } @Test - public void list_metric_with_is_custom_false() throws Exception { + public void list_metric_with_is_custom_false() { insertNewCustomMetric("1", "2"); insertNewNonCustomMetric("3"); - String result = newRequest() - .setParam(PARAM_IS_CUSTOM, "false").execute().outputAsString(); + String result = tester.newRequest() + .setParam(PARAM_IS_CUSTOM, "false").execute().getInput(); assertThat(result).doesNotContain("custom-key-1") .doesNotContain("custom-key-2") @@ -109,10 +105,10 @@ public class SearchActionTest { } @Test - public void list_metric_with_chosen_fields() throws Exception { + public void list_metric_with_chosen_fields() { insertNewCustomMetric("1"); - String result = newRequest().setParam(Param.FIELDS, "name").execute().outputAsString(); + String result = tester.newRequest().setParam(Param.FIELDS, "name").execute().getInput(); assertThat(result).contains("id", "key", "name", "type") .doesNotContain("domain") @@ -150,7 +146,4 @@ public class SearchActionTest { .setEnabled(true); } - private WsTester.TestRequest newRequest() { - return ws.newGetRequest("api/metrics", "search"); - } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/TypesActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/TypesActionTest.java index 19f23062e21..1ca85df299a 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/TypesActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/TypesActionTest.java @@ -19,26 +19,22 @@ */ package org.sonar.server.metric.ws; -import org.junit.Before; import org.junit.Test; import org.sonar.api.measures.Metric; -import org.sonar.server.ws.WsTester; +import org.sonar.server.ws.TestResponse; +import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; public class TypesActionTest { - WsTester ws; - - @Before - public void setUp() { - ws = new WsTester(new MetricsWs(new TypesAction())); - } + private TypesAction underTest = new TypesAction(); + private WsActionTester tester = new WsActionTester(underTest); @Test - public void validate_content() throws Exception { - String response = ws.newGetRequest(MetricsWs.ENDPOINT, "types").execute().outputAsString(); + public void validate_content() { + TestResponse response = tester.newRequest().execute(); - assertThat(response).contains(Metric.ValueType.names()); + assertThat(response.getInput()).contains(Metric.ValueType.names()); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/UpdateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/UpdateActionTest.java index 4d7ad291ef6..bfec040df56 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/UpdateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/UpdateActionTest.java @@ -33,7 +33,8 @@ import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.ServerException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.ws.WsTester; +import org.sonar.server.ws.TestResponse; +import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.db.measure.custom.CustomMeasureTesting.newCustomMeasureDto; @@ -61,19 +62,19 @@ public class UpdateActionTest { private DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); - private WsTester ws; + private UpdateAction underTest = new UpdateAction(dbClient, userSessionRule); + private WsActionTester tester = new WsActionTester(underTest); @Before public void setUp() { - ws = new WsTester(new MetricsWs(new UpdateAction(dbClient, userSessionRule))); userSessionRule.logIn().setSystemAdministrator(); } @Test - public void update_all_fields() throws Exception { + public void update_all_fields() { int id = insertMetric(newDefaultMetric()); - newRequest() + tester.newRequest() .setParam(PARAM_ID, String.valueOf(id)) .setParam(PARAM_KEY, "another-key") .setParam(PARAM_NAME, "another-name") @@ -92,12 +93,12 @@ public class UpdateActionTest { } @Test - public void update_one_field() throws Exception { + public void update_one_field() { int id = insertMetric(newDefaultMetric()); dbClient.customMeasureDao().insert(dbSession, newCustomMeasureDto().setMetricId(id)); dbSession.commit(); - newRequest() + tester.newRequest() .setParam(PARAM_ID, String.valueOf(id)) .setParam(PARAM_DESCRIPTION, "another-description") .execute(); @@ -112,97 +113,97 @@ public class UpdateActionTest { } @Test - public void update_return_the_full_object_with_id() throws Exception { + public void update_return_the_full_object_with_id() { int id = insertMetric(newDefaultMetric().setDescription("another-description")); - WsTester.Result requestResult = newRequest() + TestResponse requestResult = tester.newRequest() .setParam(PARAM_ID, String.valueOf(id)) .setParam(PARAM_DESCRIPTION, DEFAULT_DESCRIPTION) .execute(); dbSession.commit(); requestResult.assertJson(getClass(), "metric.json"); - assertThat(requestResult.outputAsString()).matches(".*\"id\"\\s*:\\s*\"" + id + "\".*"); + assertThat(requestResult.getInput()).matches(".*\"id\"\\s*:\\s*\"" + id + "\".*"); } @Test - public void fail_when_changing_key_for_an_existing_one() throws Exception { + public void fail_when_changing_key_for_an_existing_one() { expectedException.expect(ServerException.class); expectedException.expectMessage("The key 'metric-key' is already used by an existing metric."); insertMetric(newDefaultMetric().setKey("metric-key")); int id = insertMetric(newDefaultMetric().setKey("another-key")); - newRequest() + tester.newRequest() .setParam(PARAM_ID, String.valueOf(id)) .setParam(PARAM_KEY, "metric-key") .execute(); } @Test - public void fail_when_metric_not_in_db() throws Exception { + public void fail_when_metric_not_in_db() { expectedException.expect(ServerException.class); - newRequest().setParam(PARAM_ID, "42").execute(); + tester.newRequest().setParam(PARAM_ID, "42").execute(); } @Test - public void fail_when_metric_is_deactivated() throws Exception { + public void fail_when_metric_is_deactivated() { expectedException.expect(ServerException.class); int id = insertMetric(newDefaultMetric().setEnabled(false)); - newRequest().setParam(PARAM_ID, String.valueOf(id)).execute(); + tester.newRequest().setParam(PARAM_ID, String.valueOf(id)).execute(); } @Test - public void fail_when_metric_is_not_custom() throws Exception { + public void fail_when_metric_is_not_custom() { expectedException.expect(ServerException.class); int id = insertMetric(newDefaultMetric().setUserManaged(false)); - newRequest().setParam(PARAM_ID, String.valueOf(id)).execute(); + tester.newRequest().setParam(PARAM_ID, String.valueOf(id)).execute(); } @Test - public void fail_when_custom_measures_and_type_changed() throws Exception { + public void fail_when_custom_measures_and_type_changed() { expectedException.expect(ServerException.class); int id = insertMetric(newDefaultMetric()); dbClient.customMeasureDao().insert(dbSession, newCustomMeasureDto().setMetricId(id)); dbSession.commit(); - newRequest() + tester.newRequest() .setParam(PARAM_ID, String.valueOf(id)) .setParam(PARAM_TYPE, ValueType.BOOL.name()) .execute(); } @Test - public void fail_when_no_id() throws Exception { + public void fail_when_no_id() { expectedException.expect(IllegalArgumentException.class); - newRequest().execute(); + tester.newRequest().execute(); } @Test - public void throw_ForbiddenException_if_not_system_administrator() throws Exception { + public void throw_ForbiddenException_if_not_system_administrator() { userSessionRule.logIn().setNonSystemAdministrator(); expectedException.expect(ForbiddenException.class); expectedException.expectMessage("Insufficient privileges"); - newRequest().execute(); + tester.newRequest().execute(); } @Test - public void throw_UnauthorizedException_if_not_logged_in() throws Exception { + public void throw_UnauthorizedException_if_not_logged_in() { userSessionRule.anonymous(); expectedException.expect(UnauthorizedException.class); expectedException.expectMessage("Authentication is required"); - newRequest().execute(); + tester.newRequest().execute(); } @Test - public void fail_when_metric_key_is_not_well_formatted() throws Exception { + public void fail_when_metric_key_is_not_well_formatted() { int id = insertMetric(newDefaultMetric()); dbClient.customMeasureDao().insert(dbSession, newCustomMeasureDto().setMetricId(id)); dbSession.commit(); @@ -210,7 +211,7 @@ public class UpdateActionTest { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Malformed metric key 'not well formatted key'. Allowed characters are alphanumeric, '-', '_', with at least one non-digit."); - newRequest() + tester.newRequest() .setParam(PARAM_ID, String.valueOf(id)) .setParam(PARAM_KEY, "not well formatted key") .execute(); @@ -233,7 +234,4 @@ public class UpdateActionTest { return metricDto.getId(); } - private WsTester.TestRequest newRequest() { - return ws.newPostRequest("api/metrics", "update"); - } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/notification/ws/NotificationsWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/notification/ws/NotificationsWsTest.java index e703452d4f3..98d7ef2a661 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/notification/ws/NotificationsWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/notification/ws/NotificationsWsTest.java @@ -24,20 +24,22 @@ import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Controller; -import org.sonar.server.ws.WsTester; import static org.assertj.core.api.Assertions.assertThat; public class NotificationsWsTest { private NotificationsWsAction action = new FakeNotificationAction(); private NotificationsWsAction[] actions = {action}; - private WsTester ws = new WsTester(new NotificationsWs(actions)); - - private Controller underTest = ws.controller("api/notifications"); + private NotificationsWs underTest = new NotificationsWs(actions); @Test public void definition() { - assertThat(underTest.path()).isEqualTo("api/notifications"); + WebService.Context context = new WebService.Context(); + + underTest.define(context); + + Controller controller = context.controller("api/notifications"); + assertThat(controller.path()).isEqualTo("api/notifications"); } private static class FakeNotificationAction implements NotificationsWsAction { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/PermissionsWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/PermissionsWsTest.java index d11aaada6cb..01c696b6eda 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/PermissionsWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/PermissionsWsTest.java @@ -19,80 +19,38 @@ */ package org.sonar.server.permission.ws; -import org.junit.Rule; import org.junit.Test; -import org.sonar.api.resources.Qualifiers; +import org.sonar.api.server.ws.Request; +import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; -import org.sonar.db.DbTester; -import org.sonar.db.component.ResourceTypesRule; -import org.sonar.server.component.ComponentFinder; -import org.sonar.server.issue.AvatarResolverImpl; -import org.sonar.server.organization.TestDefaultOrganizationProvider; -import org.sonar.server.permission.PermissionService; -import org.sonar.server.permission.PermissionServiceImpl; -import org.sonar.server.permission.RequestValidator; -import org.sonar.server.permission.ws.template.TemplateGroupsAction; -import org.sonar.server.permission.ws.template.TemplateUsersAction; -import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.usergroups.DefaultGroupFinder; -import org.sonar.server.usergroups.ws.GroupWsSupport; -import org.sonar.server.ws.WsTester; import static org.assertj.core.api.Assertions.assertThat; -import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION; public class PermissionsWsTest { - @Rule - public DbTester db = DbTester.create(); - @Rule - public UserSessionRule userSession = UserSessionRule.standalone(); + private PermissionsWs underTest = new PermissionsWs(new PermissionsWsAction() { + @Override + public void define(WebService.NewController context) { + context.createAction("foo").setHandler(this); + } - private TestDefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db); - private final ResourceTypesRule resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); - private final GroupWsSupport groupWsSupport = new GroupWsSupport(db.getDbClient(), defaultOrganizationProvider, new DefaultGroupFinder(db.getDbClient())); - private final PermissionWsSupport wsSupport = new PermissionWsSupport(db.getDbClient(), new ComponentFinder(db.getDbClient(), resourceTypes), groupWsSupport); + @Override + public void handle(Request request, Response response) { - private PermissionService permissionService = new PermissionServiceImpl(resourceTypes); - private WsParameters wsParameters = new WsParameters(permissionService); - private RequestValidator requestValidator = new RequestValidator(permissionService); - - - private WsTester underTest = new WsTester(new PermissionsWs( - new TemplateUsersAction(db.getDbClient(), userSession, wsSupport, new AvatarResolverImpl(), wsParameters, requestValidator), - new TemplateGroupsAction(db.getDbClient(), userSession, wsSupport, wsParameters, requestValidator))); + } + }); @Test public void define_controller() { - WebService.Controller controller = controller(); + WebService.Context context = new WebService.Context(); + + underTest.define(context); + + WebService.Controller controller = context.controller("api/permissions"); assertThat(controller).isNotNull(); assertThat(controller.description()).isNotEmpty(); assertThat(controller.since()).isEqualTo("3.7"); - assertThat(controller.actions()).hasSize(2); + assertThat(controller.actions()).hasSize(1); } - @Test - public void define_template_users() { - WebService.Action action = controller().action("template_users"); - - assertThat(action).isNotNull(); - assertThat(action.isPost()).isFalse(); - assertThat(action.isInternal()).isTrue(); - assertThat(action.since()).isEqualTo("5.2"); - assertThat(action.param(PARAM_PERMISSION).isRequired()).isFalse(); - } - - @Test - public void define_template_groups() { - WebService.Action action = controller().action("template_groups"); - - assertThat(action).isNotNull(); - assertThat(action.isPost()).isFalse(); - assertThat(action.isInternal()).isTrue(); - assertThat(action.since()).isEqualTo("5.2"); - } - - private WebService.Controller controller() { - return underTest.controller("api/permissions"); - } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/TemplateGroupsActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/TemplateGroupsActionTest.java index ea4a08f9b90..387b4b18c2c 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/TemplateGroupsActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/TemplateGroupsActionTest.java @@ -23,6 +23,7 @@ import javax.annotation.Nullable; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; +import org.sonar.api.server.ws.WebService; import org.sonar.core.permission.GlobalPermissions; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.organization.OrganizationDto; @@ -68,6 +69,17 @@ public class TemplateGroupsActionTest extends BasePermissionWsTest clazz = AvailableActionTest.class; - return clazz.getResource(clazz.getSimpleName() + "/" + s); - } - protected static PluginUpdate pluginUpdate(String key, String name) { return PluginUpdate.createWithStatus( new Release(Plugin.factory(key).setName(name), Version.create("1.0")), diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/AvailableActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/AvailableActionTest.java index 7a2af42d577..357f54efdfd 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/AvailableActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/AvailableActionTest.java @@ -27,8 +27,8 @@ import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.DateUtils; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.tester.UserSessionRule; +import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; -import org.sonar.server.ws.WsTester; import org.sonar.updatecenter.common.Plugin; import org.sonar.updatecenter.common.PluginUpdate; import org.sonar.updatecenter.common.Release; @@ -67,27 +67,19 @@ public class AvailableActionTest extends AbstractUpdateCenterBasedPluginsWsActio public ExpectedException expectedException = ExpectedException.none(); private AvailableAction underTest = new AvailableAction(userSession, updateCenterFactory); + private WsActionTester tester = new WsActionTester(underTest); @Test public void action_available_is_defined() { - logInAsSystemAdministrator(); - WsTester wsTester = new WsTester(); - WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY); - - underTest.define(newController); - newController.done(); - - WebService.Controller controller = wsTester.controller(DUMMY_CONTROLLER_KEY); - assertThat(controller.actions()).extracting("key").containsExactly("available"); - - WebService.Action action = controller.actions().iterator().next(); + WebService.Action action = tester.getDef(); + assertThat(action.key()).isEqualTo("available"); assertThat(action.isPost()).isFalse(); assertThat(action.description()).isNotEmpty(); assertThat(action.responseExample()).isNotNull(); } @Test - public void verify_example() throws Exception { + public void verify_example() { logInAsSystemAdministrator(); when(updateCenter.findAvailablePlugins()).thenReturn(of( pluginUpdate(release(Plugin.factory("abap") @@ -113,56 +105,55 @@ public class AvailableActionTest extends AbstractUpdateCenterBasedPluginsWsActio .addOutgoingDependency(release(Plugin.factory("java").setName("Java").setDescription("SonarQube rule engine."), "0.3.6")), COMPATIBLE))); - underTest.handle(request, response); + TestResponse response = tester.newRequest().execute(); - WsActionTester actionTester = new WsActionTester(underTest); - assertJson(response.outputAsString()).isSimilarTo(actionTester.getDef().responseExampleAsString()); + assertJson(response.getInput()).isSimilarTo(tester.getDef().responseExampleAsString()); } @Test - public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() throws Exception { + public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() { expectedException.expect(ForbiddenException.class); - underTest.handle(request, response); + tester.newRequest().execute(); } @Test - public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() throws Exception { + public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() { userSession.logIn().setNonSystemAdministrator(); expectedException.expect(ForbiddenException.class); - underTest.handle(request, response); + tester.newRequest().execute(); } @Test - public void empty_array_is_returned_when_there_is_no_plugin_available() throws Exception { + public void empty_array_is_returned_when_there_is_no_plugin_available() { logInAsSystemAdministrator(); - underTest.handle(request, response); - assertJson(response.outputAsString()).withStrictArrayOrder().isSimilarTo(JSON_EMPTY_PLUGIN_LIST); + TestResponse response = tester.newRequest().execute(); + + assertJson(response.getInput()).withStrictArrayOrder().isSimilarTo(JSON_EMPTY_PLUGIN_LIST); } @Test - public void empty_array_is_returned_when_update_center_is_not_accessible() throws Exception { + public void empty_array_is_returned_when_update_center_is_not_accessible() { logInAsSystemAdministrator(); when(updateCenterFactory.getUpdateCenter(anyBoolean())).thenReturn(Optional.absent()); - underTest.handle(request, response); + TestResponse response = tester.newRequest().execute(); - assertJson(response.outputAsString()).withStrictArrayOrder().isSimilarTo(JSON_EMPTY_PLUGIN_LIST); + assertJson(response.getInput()).withStrictArrayOrder().isSimilarTo(JSON_EMPTY_PLUGIN_LIST); } @Test - public void verify_properties_displayed_in_json_per_plugin() throws Exception { + public void verify_properties_displayed_in_json_per_plugin() { logInAsSystemAdministrator(); when(updateCenter.findAvailablePlugins()).thenReturn(of( pluginUpdate(FULL_PROPERTIES_PLUGIN_RELEASE, COMPATIBLE))); - underTest.handle(request, response); + TestResponse response = tester.newRequest().execute(); - assertJson(response.outputAsString()) - .isSimilarTo( + response.assertJson( "{" + " \"plugins\": [" + " {" + @@ -201,36 +192,36 @@ public class AvailableActionTest extends AbstractUpdateCenterBasedPluginsWsActio } @Test - public void status_COMPATIBLE_is_displayed_COMPATIBLE_in_JSON() throws Exception { + public void status_COMPATIBLE_is_displayed_COMPATIBLE_in_JSON() { logInAsSystemAdministrator(); checkStatusDisplayedInJson(COMPATIBLE, "COMPATIBLE"); } @Test - public void status_INCOMPATIBLE_is_displayed_INCOMPATIBLE_in_JSON() throws Exception { + public void status_INCOMPATIBLE_is_displayed_INCOMPATIBLE_in_JSON() { logInAsSystemAdministrator(); checkStatusDisplayedInJson(INCOMPATIBLE, "INCOMPATIBLE"); } @Test - public void status_REQUIRE_SONAR_UPGRADE_is_displayed_REQUIRES_SYSTEM_UPGRADE_in_JSON() throws Exception { + public void status_REQUIRE_SONAR_UPGRADE_is_displayed_REQUIRES_SYSTEM_UPGRADE_in_JSON() { logInAsSystemAdministrator(); checkStatusDisplayedInJson(REQUIRE_SONAR_UPGRADE, "REQUIRES_SYSTEM_UPGRADE"); } @Test - public void status_DEPENDENCIES_REQUIRE_SONAR_UPGRADE_is_displayed_DEPS_REQUIRE_SYSTEM_UPGRADE_in_JSON() throws Exception { + public void status_DEPENDENCIES_REQUIRE_SONAR_UPGRADE_is_displayed_DEPS_REQUIRE_SYSTEM_UPGRADE_in_JSON() { logInAsSystemAdministrator(); checkStatusDisplayedInJson(DEPENDENCIES_REQUIRE_SONAR_UPGRADE, "DEPS_REQUIRE_SYSTEM_UPGRADE"); } - private void checkStatusDisplayedInJson(PluginUpdate.Status status, String expectedValue) throws Exception { + private void checkStatusDisplayedInJson(PluginUpdate.Status status, String expectedValue) { when(updateCenter.findAvailablePlugins()).thenReturn(of( pluginUpdate(release(PLUGIN_1, "1.0.0"), status))); - underTest.handle(request, response); + TestResponse response = tester.newRequest().execute(); - assertJson(response.outputAsString()).isSimilarTo( + response.assertJson( "{" + " \"plugins\": [" + " {" + diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/CancelAllActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/CancelAllActionTest.java index fc175e09771..f66e25a8b64 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/CancelAllActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/CancelAllActionTest.java @@ -22,13 +22,13 @@ package org.sonar.server.plugins.ws; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.WebService; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.plugins.PluginDownloader; import org.sonar.server.plugins.PluginUninstaller; import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.ws.WsTester; +import org.sonar.server.ws.TestResponse; +import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -36,8 +36,6 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class CancelAllActionTest { - private static final String DUMMY_CONTROLLER_KEY = "dummy"; - @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); @Rule @@ -46,22 +44,12 @@ public class CancelAllActionTest { private PluginDownloader pluginDownloader = mock(PluginDownloader.class); private PluginUninstaller pluginUninstaller = mock(PluginUninstaller.class); private CancelAllAction underTest = new CancelAllAction(pluginDownloader, pluginUninstaller, userSessionRule); - - private Request request = mock(Request.class); - private WsTester.TestResponse response = new WsTester.TestResponse(); + private WsActionTester tester = new WsActionTester(underTest); @Test public void action_cancel_all_is_defined() { - WsTester wsTester = new WsTester(); - WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY); - - underTest.define(newController); - newController.done(); - - WebService.Controller controller = wsTester.controller(DUMMY_CONTROLLER_KEY); - assertThat(controller.actions()).extracting("key").containsExactly("cancel_all"); - - WebService.Action action = controller.actions().iterator().next(); + WebService.Action action = tester.getDef(); + assertThat(action.key()).isEqualTo("cancel_all"); assertThat(action.isPost()).isTrue(); assertThat(action.description()).isNotEmpty(); assertThat(action.responseExample()).isNull(); @@ -70,32 +58,32 @@ public class CancelAllActionTest { } @Test - public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() throws Exception { + public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() { expectedException.expect(ForbiddenException.class); expectedException.expectMessage("Insufficient privileges"); - underTest.handle(request, response); + tester.newRequest().execute(); } @Test - public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() throws Exception { + public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() { userSessionRule.logIn().setNonSystemAdministrator(); expectedException.expect(ForbiddenException.class); expectedException.expectMessage("Insufficient privileges"); - underTest.handle(request, response); + tester.newRequest().execute(); } @Test - public void triggers_cancel_for_downloads_and_uninstalls() throws Exception { + public void triggers_cancel_for_downloads_and_uninstalls() { userSessionRule.logIn().setSystemAdministrator(); - underTest.handle(request, response); + TestResponse response = tester.newRequest().execute(); verify(pluginDownloader, times(1)).cancelDownloads(); verify(pluginUninstaller, times(1)).cancelUninstalls(); - assertThat(response.outputAsString()).isEmpty(); + assertThat(response.getInput()).isEmpty(); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/InstallActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/InstallActionTest.java index a8d01382d29..e83d9ab614e 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/InstallActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/InstallActionTest.java @@ -34,7 +34,8 @@ import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.plugins.PluginDownloader; import org.sonar.server.plugins.UpdateCenterMatrixFactory; import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.ws.WsTester; +import org.sonar.server.ws.TestResponse; +import org.sonar.server.ws.WsActionTester; import org.sonar.updatecenter.common.Plugin; import org.sonar.updatecenter.common.PluginUpdate; import org.sonar.updatecenter.common.Release; @@ -50,26 +51,20 @@ import static org.mockito.Mockito.when; @RunWith(DataProviderRunner.class) public class InstallActionTest { private static final String DUMMY_CONTROLLER_KEY = "dummy"; - private static final String CONTROLLER_KEY = "api/plugins"; private static final String ACTION_KEY = "install"; private static final String KEY_PARAM = "key"; private static final String PLUGIN_KEY = "pluginKey"; @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); + @Rule + public ExpectedException expectedException = ExpectedException.none(); private UpdateCenterMatrixFactory updateCenterFactory = mock(UpdateCenterMatrixFactory.class); private UpdateCenter updateCenter = mock(UpdateCenter.class); private PluginDownloader pluginDownloader = mock(PluginDownloader.class); private InstallAction underTest = new InstallAction(updateCenterFactory, pluginDownloader, userSessionRule); - - private WsTester wsTester = new WsTester(new PluginsWs(underTest)); - private WsTester.TestRequest invalidRequest = wsTester.newPostRequest(CONTROLLER_KEY, ACTION_KEY); - private WsTester.TestRequest validRequest = wsTester.newPostRequest(CONTROLLER_KEY, ACTION_KEY) - .setParam(KEY_PARAM, PLUGIN_KEY); - - @Rule - public ExpectedException expectedException = ExpectedException.none(); + private WsActionTester tester = new WsActionTester(underTest); @Before public void wireMocks() { @@ -77,38 +72,28 @@ public class InstallActionTest { } @Test - public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() throws Exception { + public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() { expectedException.expect(ForbiddenException.class); expectedException.expectMessage("Insufficient privileges"); - validRequest.execute(); + tester.newRequest().execute(); } @Test - public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() throws Exception { + public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() { userSessionRule.logIn().setNonSystemAdministrator(); expectedException.expect(ForbiddenException.class); expectedException.expectMessage("Insufficient privileges"); - validRequest.execute(); + tester.newRequest().execute(); } @Test public void action_install_is_defined() { - logInAsSystemAdministrator(); - - WsTester wsTester = new WsTester(); - WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY); - - underTest.define(newController); - newController.done(); - - WebService.Controller controller = wsTester.controller(DUMMY_CONTROLLER_KEY); - assertThat(controller.actions()).extracting("key").containsExactly(ACTION_KEY); - - WebService.Action action = controller.actions().iterator().next(); + WebService.Action action = tester.getDef(); assertThat(action.isPost()).isTrue(); + assertThat(action.key()).isEqualTo(ACTION_KEY); assertThat(action.description()).isNotEmpty(); assertThat(action.responseExample()).isNull(); @@ -120,25 +105,27 @@ public class InstallActionTest { } @Test - public void IAE_is_raised_when_key_param_is_not_provided() throws Exception { + public void IAE_is_raised_when_key_param_is_not_provided() { logInAsSystemAdministrator(); expectedException.expect(IllegalArgumentException.class); - invalidRequest.execute(); + tester.newRequest().execute(); } @Test - public void IAE_is_raised_when_there_is_no_available_plugin_for_the_key() throws Exception { + public void IAE_is_raised_when_there_is_no_available_plugin_for_the_key() { logInAsSystemAdministrator(); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("No plugin with key 'pluginKey'"); - validRequest.execute(); + tester.newRequest() + .setParam(KEY_PARAM, PLUGIN_KEY) + .execute(); } @Test @UseDataProvider("editionBundledOrganizationAndLicense") - public void IAE_is_raised_when_plugin_is_edition_bundled(String organization, String license) throws Exception { + public void IAE_is_raised_when_plugin_is_edition_bundled(String organization, String license) { logInAsSystemAdministrator(); Version version = Version.create("1.0"); when(updateCenter.findAvailablePlugins()).thenReturn(ImmutableList.of( @@ -149,7 +136,9 @@ public class InstallActionTest { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("SonarSource commercial plugin with key '" + PLUGIN_KEY + "' can only be installed as part of a SonarSource edition"); - validRequest.execute(); + tester.newRequest() + .setParam(KEY_PARAM, PLUGIN_KEY) + .execute(); } @DataProvider @@ -162,27 +151,31 @@ public class InstallActionTest { } @Test - public void IAE_is_raised_when_update_center_is_unavailable() throws Exception { + public void IAE_is_raised_when_update_center_is_unavailable() { logInAsSystemAdministrator(); when(updateCenterFactory.getUpdateCenter(anyBoolean())).thenReturn(Optional.absent()); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("No plugin with key 'pluginKey'"); - validRequest.execute(); + tester.newRequest() + .setParam(KEY_PARAM, PLUGIN_KEY) + .execute(); } @Test - public void if_plugin_is_found_available_download_is_triggered_with_latest_version_from_updatecenter() throws Exception { + public void if_plugin_is_found_available_download_is_triggered_with_latest_version_from_updatecenter() { logInAsSystemAdministrator(); Version version = Version.create("1.0"); when(updateCenter.findAvailablePlugins()).thenReturn(ImmutableList.of( PluginUpdate.createWithStatus(new Release(Plugin.factory(PLUGIN_KEY), version), PluginUpdate.Status.COMPATIBLE))); - WsTester.Result result = validRequest.execute(); + TestResponse response = tester.newRequest() + .setParam(KEY_PARAM, PLUGIN_KEY) + .execute(); verify(pluginDownloader).download(PLUGIN_KEY, version); - result.assertNoContent(); + response.assertNoContent(); } private void logInAsSystemAdministrator() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PendingActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PendingActionTest.java index aabfc8da454..7dd1d7796cf 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PendingActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PendingActionTest.java @@ -25,7 +25,6 @@ import java.util.List; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.WebService; import org.sonar.core.platform.PluginInfo; import org.sonar.server.exceptions.ForbiddenException; @@ -34,7 +33,8 @@ import org.sonar.server.plugins.PluginUninstaller; import org.sonar.server.plugins.ServerPluginRepository; import org.sonar.server.plugins.UpdateCenterMatrixFactory; import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.ws.WsTester; +import org.sonar.server.ws.TestResponse; +import org.sonar.server.ws.WsActionTester; import org.sonar.updatecenter.common.Plugin; import org.sonar.updatecenter.common.UpdateCenter; import org.sonar.updatecenter.common.Version; @@ -61,49 +61,40 @@ public class PendingActionTest { private UpdateCenterMatrixFactory updateCenterMatrixFactory = mock(UpdateCenterMatrixFactory.class, RETURNS_DEEP_STUBS); private PendingAction underTest = new PendingAction(userSession, pluginDownloader, serverPluginRepository, pluginUninstaller, updateCenterMatrixFactory); - private Request request = mock(Request.class); - private WsTester.TestResponse response = new WsTester.TestResponse(); + private WsActionTester tester = new WsActionTester(underTest); @Test public void action_pending_is_defined() { - logInAsSystemAdministrator(); - WsTester wsTester = new WsTester(); - WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY); - - underTest.define(newController); - newController.done(); - - WebService.Controller controller = wsTester.controller(DUMMY_CONTROLLER_KEY); - assertThat(controller.actions()).extracting("key").containsExactly("pending"); - - WebService.Action action = controller.actions().iterator().next(); + WebService.Action action = tester.getDef(); assertThat(action.isPost()).isFalse(); + assertThat(action.key()).isEqualTo("pending"); assertThat(action.description()).isNotEmpty(); assertThat(action.responseExample()).isNotNull(); } @Test - public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() throws Exception { + public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() { expectedException.expect(ForbiddenException.class); - underTest.handle(request, response); + tester.newRequest().execute(); } @Test - public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() throws Exception { + public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() { userSession.logIn().setNonSystemAdministrator(); expectedException.expect(ForbiddenException.class); - underTest.handle(request, response); + tester.newRequest().execute(); } @Test - public void empty_arrays_are_returned_when_there_nothing_pending() throws Exception { + public void empty_arrays_are_returned_when_there_nothing_pending() { logInAsSystemAdministrator(); - underTest.handle(request, response); - assertJson(response.outputAsString()).withStrictArrayOrder().isSimilarTo( + TestResponse response = tester.newRequest().execute(); + + assertJson(response.getInput()).withStrictArrayOrder().isSimilarTo( "{" + " \"installing\": []," + " \"removing\": []," + @@ -112,13 +103,13 @@ public class PendingActionTest { } @Test - public void empty_arrays_are_returned_when_update_center_is_unavailable() throws Exception { + public void empty_arrays_are_returned_when_update_center_is_unavailable() { logInAsSystemAdministrator(); when(updateCenterMatrixFactory.getUpdateCenter(false)).thenReturn(Optional.absent()); - underTest.handle(request, response); + TestResponse response = tester.newRequest().execute(); - assertJson(response.outputAsString()).withStrictArrayOrder().isSimilarTo( + assertJson(response.getInput()).withStrictArrayOrder().isSimilarTo( "{" + " \"installing\": []," + " \"removing\": []," + @@ -127,14 +118,14 @@ public class PendingActionTest { } @Test - public void verify_properties_displayed_in_json_per_installing_plugin() throws Exception { + public void verify_properties_displayed_in_json_per_installing_plugin() { logInAsSystemAdministrator(); newUpdateCenter("scmgit"); when(pluginDownloader.getDownloadedPlugins()).thenReturn(of(newScmGitPluginInfo())); - underTest.handle(request, response); + TestResponse response = tester.newRequest().execute(); - assertJson(response.outputAsString()).isSimilarTo( + response.assertJson( "{" + " \"installing\": " + " [" + @@ -158,13 +149,13 @@ public class PendingActionTest { } @Test - public void verify_properties_displayed_in_json_per_removing_plugin() throws Exception { + public void verify_properties_displayed_in_json_per_removing_plugin() { logInAsSystemAdministrator(); when(pluginUninstaller.getUninstalledPlugins()).thenReturn(of(newScmGitPluginInfo())); - underTest.handle(request, response); + TestResponse response = tester.newRequest().execute(); - assertJson(response.outputAsString()).isSimilarTo( + response.assertJson( "{" + " \"installing\": []," + " \"updating\": []," + @@ -187,15 +178,15 @@ public class PendingActionTest { } @Test - public void verify_properties_displayed_in_json_per_updating_plugin() throws Exception { + public void verify_properties_displayed_in_json_per_updating_plugin() { logInAsSystemAdministrator(); newUpdateCenter("scmgit"); when(serverPluginRepository.getPluginInfos()).thenReturn(of(newScmGitPluginInfo())); when(pluginDownloader.getDownloadedPlugins()).thenReturn(of(newScmGitPluginInfo())); - underTest.handle(request, response); + TestResponse response = tester.newRequest().execute(); - assertJson(response.outputAsString()).isSimilarTo( + response.assertJson( "{" + " \"installing\": []," + " \"removing\": []," + @@ -209,7 +200,7 @@ public class PendingActionTest { } @Test - public void verify_properties_displayed_in_json_per_installing_removing_and_updating_plugins() throws Exception { + public void verify_properties_displayed_in_json_per_installing_removing_and_updating_plugins() { logInAsSystemAdministrator(); PluginInfo installed = newPluginInfo("java"); PluginInfo removedPlugin = newPluginInfo("js"); @@ -220,9 +211,9 @@ public class PendingActionTest { when(pluginUninstaller.getUninstalledPlugins()).thenReturn(of(removedPlugin)); when(pluginDownloader.getDownloadedPlugins()).thenReturn(of(newPlugin, installed)); - underTest.handle(request, response); + TestResponse response = tester.newRequest().execute(); - assertJson(response.outputAsString()).isSimilarTo( + response.assertJson( "{" + " \"installing\":" + " [" + @@ -246,16 +237,16 @@ public class PendingActionTest { } @Test - public void installing_plugins_are_sorted_by_name_then_key_and_are_unique() throws Exception { + public void installing_plugins_are_sorted_by_name_then_key_and_are_unique() { logInAsSystemAdministrator(); when(pluginDownloader.getDownloadedPlugins()).thenReturn(of( newPluginInfo(0).setName("Foo"), newPluginInfo(3).setName("Bar"), newPluginInfo(2).setName("Bar"))); - underTest.handle(request, response); + TestResponse response = tester.newRequest().execute(); - assertJson(response.outputAsString()).withStrictArrayOrder().isSimilarTo( + assertJson(response.getInput()).withStrictArrayOrder().isSimilarTo( "{" + " \"installing\": " + " [" + @@ -278,16 +269,16 @@ public class PendingActionTest { } @Test - public void removing_plugins_are_sorted_and_unique() throws Exception { + public void removing_plugins_are_sorted_and_unique() { logInAsSystemAdministrator(); when(pluginUninstaller.getUninstalledPlugins()).thenReturn(of( newPluginInfo(0).setName("Foo"), newPluginInfo(3).setName("Bar"), newPluginInfo(2).setName("Bar"))); - underTest.handle(request, response); + TestResponse response = tester.newRequest().execute(); - assertJson(response.outputAsString()).withStrictArrayOrder().isSimilarTo( + assertJson(response.getInput()).withStrictArrayOrder().isSimilarTo( "{" + " \"installing\": []," + " \"updating\": []," + diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PluginWSCommonsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PluginWSCommonsTest.java index cef589d415f..6b34ddcdc7f 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PluginWSCommonsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PluginWSCommonsTest.java @@ -29,7 +29,7 @@ import org.sonar.core.platform.PluginInfo; import org.sonar.db.plugin.PluginDto; import org.sonar.server.plugins.InstalledPlugin; import org.sonar.server.plugins.InstalledPlugin.FileAndMd5; -import org.sonar.server.ws.WsTester; +import org.sonar.server.ws.DumbResponse; import org.sonar.updatecenter.common.Plugin; import org.sonar.updatecenter.common.PluginUpdate; import org.sonar.updatecenter.common.Release; @@ -49,11 +49,12 @@ public class PluginWSCommonsTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); - private WsTester.TestResponse response = new WsTester.TestResponse(); + private DumbResponse response = new DumbResponse(); private JsonWriter jsonWriter = response.newJsonWriter(); @Test public void verify_properties_written_by_writePluginMetadata() { + PluginWSCommons.writePluginInfo(jsonWriter, gitPluginInfo(), null, null, null); jsonWriter.close(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PluginsWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PluginsWsTest.java index 92e14c6313e..2d5913754fc 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PluginsWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PluginsWsTest.java @@ -23,17 +23,19 @@ import org.junit.Test; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; -import org.sonar.server.ws.WsTester; import static org.assertj.core.api.Assertions.assertThat; public class PluginsWsTest { - private WsTester tester = new WsTester(new PluginsWs(new DummyPluginsWsAction())); + private PluginsWs underTest = new PluginsWs(new DummyPluginsWsAction()); @Test public void defines_controller_and_binds_PluginsWsActions() { - WebService.Controller controller = tester.controller("api/plugins"); + WebService.Context context = new WebService.Context(); + underTest.define(context); + + WebService.Controller controller = context.controller("api/plugins"); assertThat(controller).isNotNull(); assertThat(controller.since()).isEqualTo("5.2"); assertThat(controller.description()).isNotEmpty(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UninstallActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UninstallActionTest.java index cd7388102da..1f79265b300 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UninstallActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UninstallActionTest.java @@ -26,14 +26,14 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; -import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.WebService; import org.sonar.core.platform.PluginInfo; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.plugins.PluginUninstaller; import org.sonar.server.plugins.ServerPluginRepository; import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.ws.WsTester; +import org.sonar.server.ws.TestResponse; +import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -43,7 +43,6 @@ import static org.mockito.Mockito.when; @RunWith(DataProviderRunner.class) public class UninstallActionTest { - private static final String DUMMY_CONTROLLER_KEY = "dummy"; private static final String CONTROLLER_KEY = "api/plugins"; private static final String ACTION_KEY = "uninstall"; private static final String KEY_PARAM = "key"; @@ -57,44 +56,30 @@ public class UninstallActionTest { private ServerPluginRepository serverPluginRepository = mock(ServerPluginRepository.class); private PluginUninstaller pluginUninstaller = mock(PluginUninstaller.class); private UninstallAction underTest = new UninstallAction(serverPluginRepository, pluginUninstaller, userSessionRule); - - private WsTester wsTester = new WsTester(new PluginsWs(underTest)); - private Request invalidRequest = wsTester.newGetRequest(CONTROLLER_KEY, ACTION_KEY); - private Request validRequest = wsTester.newGetRequest(CONTROLLER_KEY, ACTION_KEY).setParam(KEY_PARAM, PLUGIN_KEY); - private WsTester.TestResponse response = new WsTester.TestResponse(); + private WsActionTester tester = new WsActionTester(underTest); @Test - public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() throws Exception { + public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() { expectedException.expect(ForbiddenException.class); expectedException.expectMessage("Insufficient privileges"); - underTest.handle(validRequest, response); + tester.newRequest().execute(); } @Test - public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() throws Exception { + public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() { userSessionRule.logIn().setNonSystemAdministrator(); expectedException.expect(ForbiddenException.class); expectedException.expectMessage("Insufficient privileges"); - underTest.handle(validRequest, response); + tester.newRequest().execute(); } @Test public void action_uninstall_is_defined() { - logInAsSystemAdministrator(); - - WsTester wsTester = new WsTester(); - WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY); - - underTest.define(newController); - newController.done(); - - WebService.Controller controller = wsTester.controller(DUMMY_CONTROLLER_KEY); - assertThat(controller.actions()).extracting("key").containsExactly(ACTION_KEY); - - WebService.Action action = controller.actions().iterator().next(); + WebService.Action action = tester.getDef(); + assertThat(action.key()).isEqualTo(ACTION_KEY); assertThat(action.isPost()).isTrue(); assertThat(action.description()).isNotEmpty(); assertThat(action.responseExample()).isNull(); @@ -107,27 +92,29 @@ public class UninstallActionTest { } @Test - public void IAE_is_raised_when_key_param_is_not_provided() throws Exception { + public void IAE_is_raised_when_key_param_is_not_provided() { logInAsSystemAdministrator(); expectedException.expect(IllegalArgumentException.class); - underTest.handle(invalidRequest, response); + tester.newRequest().execute(); } @Test - public void do_not_attempt_uninstall_if_no_plugin_in_repository_for_specified_key() throws Exception { + public void do_not_attempt_uninstall_if_no_plugin_in_repository_for_specified_key() { logInAsSystemAdministrator(); when(serverPluginRepository.getPluginInfo(PLUGIN_KEY)).thenReturn(null); - underTest.handle(validRequest, response); + tester.newRequest() + .setParam(KEY_PARAM, PLUGIN_KEY) + .execute(); verifyZeroInteractions(pluginUninstaller); } @Test @UseDataProvider("editionBundledOrganizationAndLicense") - public void IAE_is_raised_when_plugin_is_installed_and_is_edition_bundled(String organization, String license) throws Exception { + public void IAE_is_raised_when_plugin_is_installed_and_is_edition_bundled(String organization, String license) { logInAsSystemAdministrator(); when(serverPluginRepository.getPluginInfo(PLUGIN_KEY)) .thenReturn(new PluginInfo(PLUGIN_KEY) @@ -137,7 +124,9 @@ public class UninstallActionTest { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("SonarSource commercial plugin with key '" + PLUGIN_KEY + "' can only be uninstalled as part of a SonarSource edition"); - underTest.handle(validRequest, response); + tester.newRequest() + .setParam(KEY_PARAM, PLUGIN_KEY) + .execute(); } @DataProvider @@ -150,14 +139,16 @@ public class UninstallActionTest { } @Test - public void if_plugin_is_installed_uninstallation_is_triggered() throws Exception { + public void if_plugin_is_installed_uninstallation_is_triggered() { logInAsSystemAdministrator(); when(serverPluginRepository.getPluginInfo(PLUGIN_KEY)).thenReturn(new PluginInfo(PLUGIN_KEY)); - underTest.handle(validRequest, response); + TestResponse response = tester.newRequest() + .setParam(KEY_PARAM, PLUGIN_KEY) + .execute(); verify(pluginUninstaller).uninstall(PLUGIN_KEY); - assertThat(response.outputAsString()).isEmpty(); + assertThat(response.getInput()).isEmpty(); } private void logInAsSystemAdministrator() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UpdateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UpdateActionTest.java index 4fa59d1e369..576608be08c 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UpdateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UpdateActionTest.java @@ -25,13 +25,13 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.WebService; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.plugins.PluginDownloader; import org.sonar.server.plugins.UpdateCenterMatrixFactory; import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.ws.WsTester; +import org.sonar.server.ws.TestResponse; +import org.sonar.server.ws.WsActionTester; import org.sonar.updatecenter.common.Plugin; import org.sonar.updatecenter.common.PluginUpdate; import org.sonar.updatecenter.common.PluginUpdate.Status; @@ -46,8 +46,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class UpdateActionTest { - private static final String DUMMY_CONTROLLER_KEY = "dummy"; - private static final String CONTROLLER_KEY = "api/plugins"; private static final String ACTION_KEY = "update"; private static final String KEY_PARAM = "key"; private static final String PLUGIN_KEY = "pluginKey"; @@ -59,11 +57,7 @@ public class UpdateActionTest { private UpdateCenter updateCenter = mock(UpdateCenter.class); private PluginDownloader pluginDownloader = mock(PluginDownloader.class); private UpdateAction underTest = new UpdateAction(updateCenterFactory, pluginDownloader, userSessionRule); - - private WsTester wsTester = new WsTester(new PluginsWs(underTest)); - private Request invalidRequest = wsTester.newGetRequest(CONTROLLER_KEY, ACTION_KEY); - private Request validRequest = wsTester.newGetRequest(CONTROLLER_KEY, ACTION_KEY).setParam(KEY_PARAM, PLUGIN_KEY); - private WsTester.TestResponse response = new WsTester.TestResponse(); + private WsActionTester tester = new WsActionTester(underTest); @Rule public ExpectedException expectedException = ExpectedException.none(); @@ -74,37 +68,27 @@ public class UpdateActionTest { } @Test - public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() throws Exception { + public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() { expectedException.expect(ForbiddenException.class); expectedException.expectMessage("Insufficient privileges"); - underTest.handle(validRequest, response); + tester.newRequest().execute(); } @Test - public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() throws Exception { + public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() { userSessionRule.logIn().setNonSystemAdministrator(); expectedException.expect(ForbiddenException.class); expectedException.expectMessage("Insufficient privileges"); - underTest.handle(validRequest, response); + tester.newRequest().execute(); } @Test public void action_update_is_defined() { - logInAsSystemAdministrator(); - - WsTester wsTester = new WsTester(); - WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY); - - underTest.define(newController); - newController.done(); - - WebService.Controller controller = wsTester.controller(DUMMY_CONTROLLER_KEY); - assertThat(controller.actions()).extracting("key").containsExactly(ACTION_KEY); - - WebService.Action action = controller.actions().iterator().next(); + WebService.Action action = tester.getDef(); + assertThat(action.key()).isEqualTo(ACTION_KEY); assertThat(action.isPost()).isTrue(); assertThat(action.description()).isNotEmpty(); assertThat(action.responseExample()).isNull(); @@ -117,46 +101,52 @@ public class UpdateActionTest { } @Test - public void IAE_is_raised_when_key_param_is_not_provided() throws Exception { + public void IAE_is_raised_when_key_param_is_not_provided() { logInAsSystemAdministrator(); expectedException.expect(IllegalArgumentException.class); - underTest.handle(invalidRequest, response); + tester.newRequest().execute(); } @Test - public void IAE_is_raised_when_there_is_no_plugin_update_for_the_key() throws Exception { + public void IAE_is_raised_when_there_is_no_plugin_update_for_the_key() { logInAsSystemAdministrator(); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("No plugin with key 'pluginKey'"); - underTest.handle(validRequest, response); + tester.newRequest() + .setParam(KEY_PARAM, PLUGIN_KEY) + .execute(); } @Test - public void IAE_is_raised_when_update_center_is_unavailable() throws Exception { + public void IAE_is_raised_when_update_center_is_unavailable() { logInAsSystemAdministrator(); when(updateCenterFactory.getUpdateCenter(anyBoolean())).thenReturn(Optional.absent()); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("No plugin with key 'pluginKey'"); - underTest.handle(validRequest, response); + tester.newRequest() + .setParam(KEY_PARAM, PLUGIN_KEY) + .execute(); } @Test - public void if_plugin_has_an_update_download_is_triggered_with_latest_version_from_updatecenter() throws Exception { + public void if_plugin_has_an_update_download_is_triggered_with_latest_version_from_updatecenter() { logInAsSystemAdministrator(); Version version = Version.create("1.0"); when(updateCenter.findPluginUpdates()).thenReturn(ImmutableList.of( PluginUpdate.createWithStatus(new Release(Plugin.factory(PLUGIN_KEY), version), Status.COMPATIBLE))); - underTest.handle(validRequest, response); + TestResponse response = tester.newRequest() + .setParam(KEY_PARAM, PLUGIN_KEY) + .execute(); verify(pluginDownloader).download(PLUGIN_KEY, version); - assertThat(response.outputAsString()).isEmpty(); + assertThat(response.getInput()).isEmpty(); } private void logInAsSystemAdministrator() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UpdatesActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UpdatesActionTest.java index e4f6ad4c047..cfac72d614f 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UpdatesActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UpdatesActionTest.java @@ -26,8 +26,8 @@ import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.DateUtils; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.tester.UserSessionRule; +import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; -import org.sonar.server.ws.WsTester; import org.sonar.updatecenter.common.Plugin; import org.sonar.updatecenter.common.Release; @@ -81,73 +81,64 @@ public class UpdatesActionTest extends AbstractUpdateCenterBasedPluginsWsActionT public ExpectedException expectedException = ExpectedException.none(); private UpdatesAction underTest = new UpdatesAction(userSession, updateCenterFactory, new PluginUpdateAggregator()); + private WsActionTester tester = new WsActionTester(underTest); @Test public void action_updatable_is_defined() { - logInAsSystemAdministrator(); - - WsTester wsTester = new WsTester(); - WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY); - - underTest.define(newController); - newController.done(); - - WebService.Controller controller = wsTester.controller(DUMMY_CONTROLLER_KEY); - assertThat(controller.actions()).extracting("key").containsExactly("updates"); - - WebService.Action action = controller.actions().iterator().next(); + WebService.Action action = tester.getDef(); assertThat(action.isPost()).isFalse(); + assertThat(action.key()).isEqualTo("updates"); assertThat(action.description()).isNotEmpty(); assertThat(action.responseExample()).isNotNull(); } @Test - public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() throws Exception { + public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() { expectedException.expect(ForbiddenException.class); - underTest.handle(request, response); + tester.newRequest().execute(); } @Test - public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() throws Exception { + public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() { userSession.logIn(); expectedException.expect(ForbiddenException.class); - underTest.handle(request, response); + tester.newRequest().execute(); } @Test - public void empty_array_is_returned_when_there_is_no_plugin_available() throws Exception { + public void empty_array_is_returned_when_there_is_no_plugin_available() { logInAsSystemAdministrator(); - underTest.handle(request, response); + TestResponse response = tester.newRequest().execute(); - assertJson(response.outputAsString()).withStrictArrayOrder().isSimilarTo(JSON_EMPTY_PLUGIN_LIST); + assertJson(response.getInput()).withStrictArrayOrder().isSimilarTo(JSON_EMPTY_PLUGIN_LIST); } @Test - public void verify_response_against_example() throws Exception { + public void verify_response_against_example() { logInAsSystemAdministrator(); when(updateCenter.findPluginUpdates()).thenReturn(of( pluginUpdate(ABAP_32, COMPATIBLE), pluginUpdate(ABAP_31, INCOMPATIBLE), pluginUpdate(ANDROID_10, COMPATIBLE))); - underTest.handle(request, response); + TestResponse response = tester.newRequest().execute(); - assertJson(response.outputAsString()) + assertJson(response.getInput()) .isSimilarTo(new WsActionTester(underTest).getDef().responseExampleAsString()); } @Test - public void status_COMPATIBLE_is_displayed_COMPATIBLE_in_JSON() throws Exception { + public void status_COMPATIBLE_is_displayed_COMPATIBLE_in_JSON() { logInAsSystemAdministrator(); when(updateCenter.findPluginUpdates()).thenReturn(of( pluginUpdate(release(PLUGIN_1, "1.0.0"), COMPATIBLE))); - underTest.handle(request, response); + TestResponse response = tester.newRequest().execute(); - assertJson(response.outputAsString()).isSimilarTo( + response.assertJson( "{" + " \"plugins\": [" + " {" + @@ -162,7 +153,7 @@ public class UpdatesActionTest extends AbstractUpdateCenterBasedPluginsWsActionT } @Test - public void plugins_are_sorted_by_name_and_made_unique() throws Exception { + public void plugins_are_sorted_by_name_and_made_unique() { logInAsSystemAdministrator(); when(updateCenter.findPluginUpdates()).thenReturn(of( pluginUpdate("key2", "name2"), @@ -170,9 +161,9 @@ public class UpdatesActionTest extends AbstractUpdateCenterBasedPluginsWsActionT pluginUpdate("key0", "name0"), pluginUpdate("key1", "name1"))); - underTest.handle(request, response); + TestResponse response = tester.newRequest().execute(); - assertJson(response.outputAsString()).withStrictArrayOrder().isSimilarTo( + assertJson(response.getInput()).withStrictArrayOrder().isSimilarTo( "{" + " \"plugins\": [" + " {" + diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/project/ws/DeleteActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/project/ws/DeleteActionTest.java index d4cab6b01f8..e5fc619c5a7 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/project/ws/DeleteActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/project/ws/DeleteActionTest.java @@ -43,7 +43,9 @@ import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.project.Project; import org.sonar.server.project.ProjectLifeCycleListeners; import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.ws.WsTester; +import org.sonar.server.ws.TestRequest; +import org.sonar.server.ws.TestResponse; +import org.sonar.server.ws.WsActionTester; import static java.util.Collections.singleton; import static org.assertj.core.api.Assertions.assertThat; @@ -55,7 +57,6 @@ import static org.sonar.api.web.UserRole.ADMIN; import static org.sonar.db.permission.OrganizationPermission.ADMINISTER; import static org.sonar.db.user.UserTesting.newUserDto; import static org.sonar.server.component.TestComponentFinder.from; -import static org.sonarqube.ws.client.project.ProjectsWsParameters.CONTROLLER; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECT; public class DeleteActionTest { @@ -77,52 +78,51 @@ public class DeleteActionTest { private ComponentDbTester componentDbTester = new ComponentDbTester(db); private ComponentCleanerService componentCleanerService = mock(ComponentCleanerService.class); private ProjectLifeCycleListeners projectLifeCycleListeners = mock(ProjectLifeCycleListeners.class); - private WsTester ws = new WsTester(new ProjectsWs( - new DeleteAction( - componentCleanerService, - from(db), - dbClient, - userSessionRule, projectLifeCycleListeners))); + private DeleteAction underTest = new DeleteAction( + componentCleanerService, + from(db), + dbClient, + userSessionRule, projectLifeCycleListeners); + private WsActionTester tester = new WsActionTester(underTest); @Test - public void organization_administrator_deletes_project_by_key() throws Exception { + public void organization_administrator_deletes_project_by_key() { ComponentDto project = componentDbTester.insertPrivateProject(); userSessionRule.logIn().addPermission(ADMINISTER, project.getOrganizationUuid()); - call(newRequest().setParam(PARAM_PROJECT, project.getDbKey())); + call(tester.newRequest().setParam(PARAM_PROJECT, project.getDbKey())); assertThat(verifyDeletedKey()).isEqualTo(project.getDbKey()); verify(projectLifeCycleListeners).onProjectsDeleted(singleton(Project.from(project))); } @Test - public void project_administrator_deletes_the_project_by_key() throws Exception { + public void project_administrator_deletes_the_project_by_key() { ComponentDto project = componentDbTester.insertPrivateProject(); userSessionRule.logIn().addProjectPermission(ADMIN, project); - call(newRequest().setParam(PARAM_PROJECT, project.getDbKey())); + call(tester.newRequest().setParam(PARAM_PROJECT, project.getDbKey())); assertThat(verifyDeletedKey()).isEqualTo(project.getDbKey()); verify(projectLifeCycleListeners).onProjectsDeleted(singleton(Project.from(project))); } @Test - public void project_deletion_also_ensure_that_homepage_on_this_project_if_it_exists_is_cleared() throws Exception { + public void project_deletion_also_ensure_that_homepage_on_this_project_if_it_exists_is_cleared() { ComponentDto project = componentDbTester.insertPrivateProject(); UserDto insert = dbClient.userDao().insert(dbSession, newUserDto().setHomepageType("PROJECT").setHomepageParameter(project.uuid())); dbSession.commit(); - userSessionRule.logIn().addProjectPermission(ADMIN, project); + DeleteAction underTest = new DeleteAction( + new ComponentCleanerService(dbClient, new ResourceTypesRule().setAllQualifiers(PROJECT), + new TestProjectIndexers()), + from(db), dbClient, userSessionRule, projectLifeCycleListeners); - new WsTester(new ProjectsWs( - new DeleteAction( - new ComponentCleanerService(dbClient, new ResourceTypesRule().setAllQualifiers(PROJECT), - new TestProjectIndexers()), - from(db), dbClient, userSessionRule, projectLifeCycleListeners))) - .newPostRequest(CONTROLLER, ACTION) - .setParam(PARAM_PROJECT, project.getDbKey()) - .execute(); + new WsActionTester(underTest) + .newRequest() + .setParam(PARAM_PROJECT, project.getDbKey()) + .execute(); UserDto userReloaded = dbClient.userDao().selectUserById(dbSession, insert.getId()); assertThat(userReloaded.getHomepageType()).isNull(); @@ -130,7 +130,7 @@ public class DeleteActionTest { } @Test - public void project_deletion_also_ensure_that_webhooks_on_this_project_if_they_exists_are_deleted() throws Exception { + public void project_deletion_also_ensure_that_webhooks_on_this_project_if_they_exists_are_deleted() { ComponentDto project = componentDbTester.insertPrivateProject(); webhookDbTester.insertWebhook(project); webhookDbTester.insertWebhook(project); @@ -138,22 +138,22 @@ public class DeleteActionTest { webhookDbTester.insertWebhook(project); userSessionRule.logIn().addProjectPermission(ADMIN, project); + DeleteAction underTest = new DeleteAction( + new ComponentCleanerService(dbClient, new ResourceTypesRule().setAllQualifiers(PROJECT), + new TestProjectIndexers()), + from(db), dbClient, userSessionRule, projectLifeCycleListeners); - new WsTester(new ProjectsWs( - new DeleteAction( - new ComponentCleanerService(dbClient, new ResourceTypesRule().setAllQualifiers(PROJECT), - new TestProjectIndexers()), - from(db), dbClient, userSessionRule, projectLifeCycleListeners))) - .newPostRequest(CONTROLLER, ACTION) - .setParam(PARAM_PROJECT, project.getDbKey()) - .execute(); + new WsActionTester(underTest) + .newRequest() + .setParam(PARAM_PROJECT, project.getDbKey()) + .execute(); List webhookDtos = dbClient.webhookDao().selectByProject(dbSession, project); assertThat(webhookDtos).isEmpty(); } @Test - public void return_403_if_not_project_admin_nor_org_admin() throws Exception { + public void return_403_if_not_project_admin_nor_org_admin() { ComponentDto project = componentDbTester.insertPrivateProject(); userSessionRule.logIn() @@ -162,21 +162,21 @@ public class DeleteActionTest { .addProjectPermission(UserRole.USER, project); expectedException.expect(ForbiddenException.class); - call(newRequest().setParam(PARAM_PROJECT, project.getDbKey())); + call(tester.newRequest().setParam(PARAM_PROJECT, project.getDbKey())); } @Test - public void return_401_if_not_logged_in() throws Exception { + public void return_401_if_not_logged_in() { ComponentDto project = componentDbTester.insertPrivateProject(); userSessionRule.anonymous(); expectedException.expect(UnauthorizedException.class); - call(newRequest().setParam(PARAM_PROJECT, project.getDbKey())); + call(tester.newRequest().setParam(PARAM_PROJECT, project.getDbKey())); } @Test - public void fail_when_using_branch_db_key() throws Exception { + public void fail_when_using_branch_db_key() { ComponentDto project = db.components().insertMainBranch(); userSessionRule.logIn().addProjectPermission(UserRole.USER, project); ComponentDto branch = db.components().insertProjectBranch(project); @@ -184,7 +184,7 @@ public class DeleteActionTest { expectedException.expect(NotFoundException.class); expectedException.expectMessage(String.format("Component key '%s' not found", branch.getDbKey())); - call(newRequest().setParam(PARAM_PROJECT, branch.getDbKey())); + call(tester.newRequest().setParam(PARAM_PROJECT, branch.getDbKey())); } private String verifyDeletedKey() { @@ -193,12 +193,8 @@ public class DeleteActionTest { return argument.getValue().getDbKey(); } - private WsTester.TestRequest newRequest() { - return ws.newPostRequest(CONTROLLER, ACTION); - } - - private void call(WsTester.TestRequest request) throws Exception { - WsTester.Result result = request.execute(); + private void call(TestRequest request) { + TestResponse result = request.execute(); result.assertNoContent(); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projecttag/ws/ProjectTagsWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projecttag/ws/ProjectTagsWsTest.java index 5ad25b27b68..1ee8e790b27 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projecttag/ws/ProjectTagsWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projecttag/ws/ProjectTagsWsTest.java @@ -23,22 +23,24 @@ import org.junit.Test; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; -import org.sonar.server.ws.WsTester; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; public class ProjectTagsWsTest { - private WsTester ws = new WsTester(new ProjectTagsWs(singletonList(new FakeAction()))); - - private WebService.Controller underTest = ws.controller("api/project_tags"); + private ProjectTagsWs underTest = new ProjectTagsWs(singletonList(new FakeAction())); @Test public void definition() { - assertThat(underTest.path()).isEqualTo("api/project_tags"); - assertThat(underTest.since()).isEqualTo("6.4"); - assertThat(underTest.description()).isNotEmpty(); + WebService.Context context = new WebService.Context(); + + underTest.define(context); + + WebService.Controller controller = context.controller("api/project_tags"); + assertThat(controller.path()).isEqualTo("api/project_tags"); + assertThat(controller.since()).isEqualTo("6.4"); + assertThat(controller.description()).isNotEmpty(); } private static class FakeAction implements ProjectTagsWsAction { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/QProfileReferenceTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/QProfileReferenceTest.java index 2a4d83ccc9c..1fdb8c069ae 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/QProfileReferenceTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/QProfileReferenceTest.java @@ -22,10 +22,9 @@ package org.sonar.server.qualityprofile.ws; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.sonar.api.impl.ws.SimpleGetRequest; import org.sonar.api.resources.Languages; import org.sonar.api.server.ws.WebService; -import org.sonar.api.impl.ws.SimpleGetRequest; -import org.sonar.server.ws.WsTester; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.server.language.LanguageTesting.newLanguage; @@ -153,8 +152,8 @@ public class QProfileReferenceTest { @Test public void define_ws_parameters() { - WsTester wsTester = new WsTester(); - WebService.NewController controller = wsTester.context().createController("api/qualityprofiles"); + WebService.Context context = new WebService.Context(); + WebService.NewController controller = context.createController("api/qualityprofiles"); WebService.NewAction newAction = controller.createAction("do").setHandler((request, response) -> { }); @@ -162,7 +161,7 @@ public class QProfileReferenceTest { QProfileReference.defineParams(newAction, languages); controller.done(); - WebService.Action action = wsTester.controller("api/qualityprofiles").action("do"); + WebService.Action action = context.controller("api/qualityprofiles").action("do"); assertThat(action.param("language")).isNotNull(); assertThat(action.param("language").possibleValues()).containsOnly("java", "js"); assertThat(action.param("key")).isNotNull(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/root/ws/RootsWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/root/ws/RootsWsTest.java index a9f31b666a3..6cb9be1c93f 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/root/ws/RootsWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/root/ws/RootsWsTest.java @@ -23,18 +23,20 @@ import org.junit.Test; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; -import org.sonar.server.ws.WsTester; import static org.assertj.core.api.Assertions.assertThat; public class RootsWsTest { private RootsWs underTest = new RootsWs(new DummyRootsWsAction()); - private WsTester wsTester = new WsTester(underTest); @Test public void verify_definition() { - assertThat(wsTester.context().controllers()).hasSize(1); - WebService.Controller controller = wsTester.context().controller("api/roots"); + WebService.Context context = new WebService.Context(); + + underTest.define(context); + + assertThat(context.controllers()).hasSize(1); + WebService.Controller controller = context.controller("api/roots"); assertThat(controller.description()).isEqualTo("Manage root users"); assertThat(controller.since()).isEqualTo("6.2"); } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/RepositoriesActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/RepositoriesActionTest.java index 11dc3f30626..f7a5241e2d6 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/RepositoriesActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/RepositoriesActionTest.java @@ -26,18 +26,20 @@ import org.sonar.api.utils.System2; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.rule.RuleRepositoryDto; -import org.sonar.server.ws.WsTester; -import org.sonar.server.ws.WsTester.TestRequest; +import org.sonar.server.ws.TestRequest; +import org.sonar.server.ws.WsActionTester; import static java.util.Arrays.asList; public class RepositoriesActionTest { private static final String EMPTY_JSON_RESPONSE = "{\"repositories\":[]}"; - private WsTester wsTester; @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); + + private RepositoriesAction underTest = new RepositoriesAction(dbTester.getDbClient()); + private WsActionTester tester = new WsActionTester(underTest); @Before public void setUp() { @@ -47,26 +49,24 @@ public class RepositoriesActionTest { RuleRepositoryDto repo3 = new RuleRepositoryDto("common-ws", "ws", "SonarQube Common"); dbTester.getDbClient().ruleRepositoryDao().insertOrUpdate(dbSession, asList(repo1, repo2, repo3)); dbSession.commit(); - - wsTester = new WsTester(new RulesWs(new RepositoriesAction(dbTester.getDbClient()))); } @Test - public void should_list_repositories() throws Exception { + public void should_list_repositories() { newRequest().execute().assertJson(this.getClass(), "repositories.json"); newRequest().setParam("language", "xoo").execute().assertJson(this.getClass(), "repositories_xoo.json"); newRequest().setParam("language", "ws").execute().assertJson(this.getClass(), "repositories_ws.json"); } @Test - public void filter_repositories_by_name() throws Exception { + public void filter_repositories_by_name() { newRequest().setParam("q", "common").execute().assertJson(this.getClass(), "repositories_common.json"); newRequest().setParam("q", "squid").execute().assertJson(this.getClass(), "repositories_squid.json"); newRequest().setParam("q", "sonar").execute().assertJson(this.getClass(), "repositories_sonar.json"); } @Test - public void do_not_consider_query_as_regexp_when_filtering_repositories_by_name() throws Exception { + public void do_not_consider_query_as_regexp_when_filtering_repositories_by_name() { // invalid regexp : do not fail. Query is not a regexp. newRequest().setParam("q", "[").execute().assertJson(EMPTY_JSON_RESPONSE); @@ -76,6 +76,6 @@ public class RepositoriesActionTest { } protected TestRequest newRequest() { - return wsTester.newGetRequest("api/rules", "repositories"); + return tester.newRequest(); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/LinesActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/LinesActionTest.java index 28808af5d90..36f549a48a7 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/LinesActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/LinesActionTest.java @@ -43,8 +43,9 @@ import org.sonar.server.source.HtmlSourceDecorator; import org.sonar.server.source.SourceService; import org.sonar.server.source.index.FileSourceTesting; import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.ws.WsTester; -import org.sonar.server.ws.WsTester.TestRequest; +import org.sonar.server.ws.TestRequest; +import org.sonar.server.ws.TestResponse; +import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; import static org.mockito.ArgumentMatchers.anyString; @@ -66,46 +67,52 @@ public class LinesActionTest { private SnapshotDao snapshotDao = new SnapshotDao(); private ComponentDto privateProject; private OrganizationDto organization; - private WsTester wsTester; + private HtmlSourceDecorator htmlSourceDecorator = mock(HtmlSourceDecorator.class); + private SourceService sourceService = new SourceService(db.getDbClient(), htmlSourceDecorator); + private LinesJsonWriter linesJsonWriter = new LinesJsonWriter(htmlSourceDecorator); + private LinesAction underTest = new LinesAction(TestComponentFinder.from(db), db.getDbClient(), sourceService, linesJsonWriter, userSession); + private WsActionTester tester = new WsActionTester(underTest); @Before public void setUp() { - HtmlSourceDecorator htmlSourceDecorator = mock(HtmlSourceDecorator.class); - when(htmlSourceDecorator.getDecoratedSourceAsHtml(anyString(), anyString(), anyString())).then((Answer) - invocationOnMock -> "

" + invocationOnMock.getArguments()[0] + "

"); - LinesJsonWriter linesJsonWriter = new LinesJsonWriter(htmlSourceDecorator); - SourceService sourceService = new SourceService(db.getDbClient(), htmlSourceDecorator); - wsTester = new WsTester(new SourcesWs( - new LinesAction(TestComponentFinder.from(db), db.getDbClient(), sourceService, linesJsonWriter, userSession))); + when(htmlSourceDecorator.getDecoratedSourceAsHtml(anyString(), anyString(), anyString())) + .then((Answer) invocationOnMock -> "

" + invocationOnMock.getArguments()[0] + "

"); organization = db.organizations().insert(); privateProject = ComponentTesting.newPrivateProjectDto(organization); } @Test - public void show_source() throws Exception { + public void show_source() { ComponentDto file = insertFileWithData(FileSourceTesting.newFakeData(3).build(), privateProject); setUserWithValidPermission(file); - TestRequest request = wsTester.newGetRequest("api/sources", "lines").setParam("uuid", file.uuid()); - request.execute().assertJson(getClass(), "show_source.json"); + TestResponse response = tester.newRequest() + .setParam("uuid", file.uuid()) + .execute(); + + response.assertJson(getClass(), "show_source.json"); } @Test - public void fail_to_show_source_if_no_source_found() throws Exception { + public void fail_to_show_source_if_no_source_found() { ComponentDto file = insertFile(privateProject); setUserWithValidPermission(file); + TestRequest request = tester.newRequest() + .setParam("uuid", file.uuid()); + expectedException.expect(NotFoundException.class); - wsTester.newGetRequest("api/sources", "lines").setParam("uuid", file.uuid()).execute(); + + request.execute(); } @Test - public void show_paginated_lines() throws Exception { + public void show_paginated_lines() { ComponentDto file = insertFileWithData(FileSourceTesting.newFakeData(3).build(), privateProject); setUserWithValidPermission(file); - wsTester - .newGetRequest("api/sources", "lines") + tester + .newRequest() .setParam("uuid", file.uuid()) .setParam("from", "3") .setParam("to", "3") @@ -114,7 +121,7 @@ public class LinesActionTest { } @Test - public void branch() throws Exception { + public void branch() { ComponentDto project = db.components().insertMainBranch(); userSession.addProjectPermission(UserRole.USER, project); ComponentDto branch = db.components().insertProjectBranch(project); @@ -129,7 +136,7 @@ public class LinesActionTest { .addMembership(db.getDefaultOrganization()) .addProjectPermission(UserRole.CODEVIEWER, project, file); - wsTester.newGetRequest("api/sources", "lines") + tester.newRequest() .setParam("key", file.getKey()) .setParam("branch", file.getBranch()) .execute() @@ -137,7 +144,7 @@ public class LinesActionTest { } @Test - public void pull_request() throws Exception { + public void pull_request() { ComponentDto project = db.components().insertMainBranch(); userSession.addProjectPermission(UserRole.USER, project); ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST)); @@ -152,7 +159,7 @@ public class LinesActionTest { .addMembership(db.getDefaultOrganization()) .addProjectPermission(UserRole.CODEVIEWER, project, file); - wsTester.newGetRequest("api/sources", "lines") + tester.newRequest() .setParam("key", file.getKey()) .setParam("pullRequest", file.getPullRequest()) .execute() @@ -160,34 +167,31 @@ public class LinesActionTest { } @Test - public void fail_when_no_uuid_or_key_param() throws Exception { + public void fail_when_no_uuid_or_key_param() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Either 'uuid' or 'key' must be provided"); - TestRequest request = wsTester.newGetRequest("api/sources", "lines"); - request.execute(); + tester.newRequest().execute(); } @Test - public void fail_when_file_key_does_not_exist() throws Exception { + public void fail_when_file_key_does_not_exist() { expectedException.expect(NotFoundException.class); expectedException.expectMessage("Component key 'Foo.java' not found"); - TestRequest request = wsTester.newGetRequest("api/sources", "lines").setParam("key", "Foo.java"); - request.execute(); + tester.newRequest().setParam("key", "Foo.java").execute(); } @Test - public void fail_when_file_uuid_does_not_exist() throws Exception { + public void fail_when_file_uuid_does_not_exist() { expectedException.expect(NotFoundException.class); expectedException.expectMessage("Component id 'ABCD' not found"); - TestRequest request = wsTester.newGetRequest("api/sources", "lines").setParam("uuid", "ABCD"); - request.execute(); + tester.newRequest().setParam("uuid", "ABCD").execute(); } @Test - public void fail_when_file_is_removed() throws Exception { + public void fail_when_file_is_removed() { ComponentDto file = newFileDto(privateProject).setDbKey("file-key").setEnabled(false); db.components().insertComponents(privateProject, file); setUserWithValidPermission(file); @@ -195,35 +199,33 @@ public class LinesActionTest { expectedException.expect(NotFoundException.class); expectedException.expectMessage("Component key 'file-key' not found"); - TestRequest request = wsTester.newGetRequest("api/sources", "lines").setParam("key", "file-key"); - request.execute(); + tester.newRequest().setParam("key", "file-key").execute(); } @Test(expected = ForbiddenException.class) - public void check_permission() throws Exception { + public void check_permission() { ComponentDto file = insertFileWithData(FileSourceTesting.newFakeData(1).build(), privateProject); userSession.logIn("login"); - wsTester.newGetRequest("api/sources", "lines") + tester.newRequest() .setParam("uuid", file.uuid()) .execute(); } @Test - public void display_deprecated_fields() throws Exception { + public void display_deprecated_fields() { ComponentDto file = insertFileWithData(FileSourceTesting.newFakeData(1).build(), privateProject); setUserWithValidPermission(file); - wsTester - .newGetRequest("api/sources", "lines") + tester.newRequest() .setParam("uuid", file.uuid()) .execute() .assertJson(getClass(), "display_deprecated_fields.json"); } @Test - public void use_period_date_if_new_line_not_yet_available_in_db() throws Exception { + public void use_period_date_if_new_line_not_yet_available_in_db() { DbFileSources.Data.Builder dataBuilder = DbFileSources.Data.newBuilder(); dataBuilder.addLines(DbFileSources.Line.newBuilder().setLine(1).setScmDate(1000L).build()); dataBuilder.addLines(DbFileSources.Line.newBuilder().setLine(2).setScmDate(2000L).build()); @@ -234,15 +236,14 @@ public class LinesActionTest { ComponentDto file = insertFileWithData(dataBuilder.build(), project); setUserWithValidPermission(file); - wsTester - .newGetRequest("api/sources", "lines") + tester.newRequest() .setParam("uuid", file.uuid()) .execute() .assertJson(getClass(), "generated_isNew.json"); } @Test - public void use_deprecated_overall_coverage_fields_if_exists() throws Exception { + public void use_deprecated_overall_coverage_fields_if_exists() { DbFileSources.Data.Builder dataBuilder = DbFileSources.Data.newBuilder(); ComponentDto file = insertFileWithData(dataBuilder.addLines(newLineBuilder() .setDeprecatedOverallLineHits(1) @@ -256,15 +257,14 @@ public class LinesActionTest { .setDeprecatedItCoveredConditions(3)).build(), privateProject); setUserWithValidPermission(file); - wsTester - .newGetRequest("api/sources", "lines") + tester.newRequest() .setParam("uuid", file.uuid()) .execute() .assertJson(getClass(), "convert_deprecated_data.json"); } @Test - public void use_deprecated_ut_coverage_fields_if_exists() throws Exception { + public void use_deprecated_ut_coverage_fields_if_exists() { DbFileSources.Data.Builder dataBuilder = DbFileSources.Data.newBuilder(); ComponentDto file = insertFileWithData(dataBuilder.addLines(newLineBuilder() .setDeprecatedUtLineHits(1) @@ -275,15 +275,14 @@ public class LinesActionTest { .setDeprecatedItCoveredConditions(3)).build(), privateProject); setUserWithValidPermission(file); - TestRequest request = wsTester - .newGetRequest("api/sources", "lines") - .setParam("uuid", file.uuid()); - - request.execute().assertJson(getClass(), "convert_deprecated_data.json"); + tester.newRequest() + .setParam("uuid", file.uuid()) + .execute() + .assertJson(getClass(), "convert_deprecated_data.json"); } @Test - public void use_deprecated_it_coverage_fields_if_exists() throws Exception { + public void use_deprecated_it_coverage_fields_if_exists() { DbFileSources.Data.Builder dataBuilder = DbFileSources.Data.newBuilder(); ComponentDto file = insertFileWithData(dataBuilder.addLines(newLineBuilder() .setDeprecatedItLineHits(1) @@ -291,15 +290,14 @@ public class LinesActionTest { .setDeprecatedItCoveredConditions(3)).build(), privateProject); setUserWithValidPermission(file); - TestRequest request = wsTester - .newGetRequest("api/sources", "lines") - .setParam("uuid", file.uuid()); - - request.execute().assertJson(getClass(), "convert_deprecated_data.json"); + tester.newRequest() + .setParam("uuid", file.uuid()) + .execute() + .assertJson(getClass(), "convert_deprecated_data.json"); } @Test - public void fail_if_branch_does_not_exist() throws Exception { + public void fail_if_branch_does_not_exist() { ComponentDto project = db.components().insertPrivateProject(); ComponentDto file = db.components().insertComponent(newFileDto(project)); userSession.addProjectPermission(UserRole.USER, project); @@ -308,14 +306,14 @@ public class LinesActionTest { expectedException.expect(NotFoundException.class); expectedException.expectMessage(String.format("Component '%s' on branch '%s' not found", file.getKey(), "another_branch")); - wsTester.newGetRequest("api/sources", "lines") + tester.newRequest() .setParam("key", file.getKey()) .setParam("branch", "another_branch") .execute(); } @Test - public void fail_when_uuid_and_branch_params_are_used_together() throws Exception { + public void fail_when_uuid_and_branch_params_are_used_together() { ComponentDto project = db.components().insertPrivateProject(); ComponentDto file = db.components().insertComponent(newFileDto(project)); userSession.addProjectPermission(UserRole.USER, project); @@ -324,14 +322,14 @@ public class LinesActionTest { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Parameter 'uuid' cannot be used at the same time as 'branch' or 'pullRequest'"); - wsTester.newGetRequest("api/sources", "lines") + tester.newRequest() .setParam("uuid", file.uuid()) .setParam("branch", "another_branch") .execute(); } @Test - public void fail_when_using_branch_db_key() throws Exception { + public void fail_when_using_branch_db_key() { ComponentDto project = db.components().insertMainBranch(); ComponentDto branch = db.components().insertProjectBranch(project); userSession.addProjectPermission(UserRole.USER, project); @@ -339,13 +337,13 @@ public class LinesActionTest { expectedException.expect(NotFoundException.class); expectedException.expectMessage(format("Component key '%s' not found", branch.getDbKey())); - wsTester.newGetRequest("api/sources", "lines") + tester.newRequest() .setParam("key", branch.getDbKey()) .execute(); } @Test - public void fail_when_using_branch_uuid() throws Exception { + public void fail_when_using_branch_uuid() { ComponentDto project = db.components().insertMainBranch(); ComponentDto branch = db.components().insertProjectBranch(project); userSession.addProjectPermission(UserRole.USER, project); @@ -353,13 +351,13 @@ public class LinesActionTest { expectedException.expect(NotFoundException.class); expectedException.expectMessage(format("Component id '%s' not found", branch.uuid())); - wsTester.newGetRequest("api/sources", "lines") + tester.newRequest() .setParam("uuid", branch.uuid()) .execute(); } @Test - public void hide_scmAuthors_if_not_member_of_organization() throws Exception { + public void hide_scmAuthors_if_not_member_of_organization() { OrganizationDto org = db.organizations().insert(); ComponentDto publicProject = db.components().insertPublicProject(org); userSession.registerComponents(publicProject); @@ -370,14 +368,14 @@ public class LinesActionTest { ComponentDto file = insertFileWithData(data, publicProject); - wsTester.newGetRequest("api/sources", "lines") + tester.newRequest() .setParam("uuid", file.uuid()) .execute() .assertJson(getClass(), "hide_scmAuthors.json"); } @Test - public void show_scmAuthors_if_member_of_organization() throws Exception { + public void show_scmAuthors_if_member_of_organization() { OrganizationDto org = db.organizations().insert(); ComponentDto publicProject = db.components().insertPublicProject(org); UserDto user = db.users().insertUser(); @@ -391,7 +389,7 @@ public class LinesActionTest { ComponentDto file = insertFileWithData(data, publicProject); - wsTester.newGetRequest("api/sources", "lines") + tester.newRequest() .setParam("uuid", file.uuid()) .execute() .assertJson(getClass(), "show_scmAuthors.json"); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/ScmActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/ScmActionTest.java index db2d4f3ab03..32a018bbac0 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/ScmActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/ScmActionTest.java @@ -40,7 +40,7 @@ import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.source.HtmlSourceDecorator; import org.sonar.server.source.SourceService; import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.ws.WsTester; +import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; @@ -57,17 +57,16 @@ public class ScmActionTest { @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); - private WsTester tester; private DbClient dbClient = dbTester.getDbClient(); private DbSession dbSession = dbTester.getSession(); private ComponentDto project; private ComponentDto file; + private ScmAction underTest = new ScmAction(dbClient, new SourceService(dbTester.getDbClient(), new HtmlSourceDecorator()), + userSessionRule, TestComponentFinder.from(dbTester)); + private WsActionTester tester = new WsActionTester(underTest); @Before public void setUp() { - tester = new WsTester( - new SourcesWs(new ScmAction(dbClient, new SourceService(dbTester.getDbClient(), new HtmlSourceDecorator()), userSessionRule, TestComponentFinder.from(dbTester)))); - project = ComponentTesting.newPrivateProjectDto(dbTester.organizations().insert(), PROJECT_UUID); file = ComponentTesting.newFileDto(project, null, FILE_UUID).setDbKey(FILE_KEY); dbClient.componentDao().insert(dbTester.getSession(), project, file); @@ -75,7 +74,7 @@ public class ScmActionTest { } @Test - public void show_scm() throws Exception { + public void show_scm() { userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project, file); dbTester.getDbClient().fileSourceDao().insert(dbSession, new FileSourceDto() @@ -85,12 +84,14 @@ public class ScmActionTest { newSourceLine("julien", "123-456-789", DateUtils.parseDateTime("2015-03-30T12:34:56+0000"), 1)).build())); dbSession.commit(); - WsTester.TestRequest request = tester.newGetRequest("api/sources", "scm").setParam("key", FILE_KEY); - request.execute().assertJson(getClass(), "show_scm.json"); + tester.newRequest() + .setParam("key", FILE_KEY) + .execute() + .assertJson(getClass(), "show_scm.json"); } @Test - public void show_scm_from_given_range_lines() throws Exception { + public void show_scm_from_given_range_lines() { userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project, file); dbTester.getDbClient().fileSourceDao().insert(dbSession, new FileSourceDto() @@ -104,12 +105,16 @@ public class ScmActionTest { .build())); dbSession.commit(); - WsTester.TestRequest request = tester.newGetRequest("api/sources", "scm").setParam("key", FILE_KEY).setParam("from", "2").setParam("to", "3"); - request.execute().assertJson(getClass(), "show_scm_from_given_range_lines.json"); + tester.newRequest() + .setParam("key", FILE_KEY) + .setParam("from", "2") + .setParam("to", "3") + .execute() + .assertJson(getClass(), "show_scm_from_given_range_lines.json"); } @Test - public void not_group_lines_by_commit() throws Exception { + public void not_group_lines_by_commit() { userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project, file); // lines 1 and 2 are the same commit, but not 3 (different date) @@ -124,13 +129,15 @@ public class ScmActionTest { .build())); dbSession.commit(); - WsTester.TestRequest request = tester.newGetRequest("api/sources", "scm").setParam("key", FILE_KEY).setParam("commits_by_line", - "true"); - request.execute().assertJson(getClass(), "not_group_lines_by_commit.json"); + tester.newRequest() + .setParam("key", FILE_KEY) + .setParam("commits_by_line","true") + .execute() + .assertJson(getClass(), "not_group_lines_by_commit.json"); } @Test - public void group_lines_by_commit() throws Exception { + public void group_lines_by_commit() { userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project, file); // lines 1 and 2 are the same commit, but not 3 (different date) @@ -145,13 +152,15 @@ public class ScmActionTest { .build())); dbSession.commit(); - WsTester.TestRequest request = tester.newGetRequest("api/sources", "scm").setParam("key", FILE_KEY).setParam("commits_by_line", - "false"); - request.execute().assertJson(getClass(), "group_lines_by_commit.json"); + tester.newRequest() + .setParam("key", FILE_KEY) + .setParam("commits_by_line","false") + .execute() + .assertJson(getClass(), "group_lines_by_commit.json"); } @Test - public void accept_negative_value_in_from_parameter() throws Exception { + public void accept_negative_value_in_from_parameter() { userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project, file); dbTester.getDbClient().fileSourceDao().insert(dbSession, new FileSourceDto() @@ -165,13 +174,16 @@ public class ScmActionTest { .build())); dbSession.commit(); - WsTester.TestRequest request = tester.newGetRequest("api/sources", "scm").setParam("key", FILE_KEY).setParam("from", - "-2").setParam("to", "3"); - request.execute().assertJson(getClass(), "accept_negative_value_in_from_parameter.json"); + tester.newRequest() + .setParam("key", FILE_KEY) + .setParam("from","-2") + .setParam("to", "3") + .execute() + .assertJson(getClass(), "accept_negative_value_in_from_parameter.json"); } @Test - public void return_empty_value_when_no_scm() throws Exception { + public void return_empty_value_when_no_scm() { userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project, file); dbTester.getDbClient().fileSourceDao().insert(dbSession, new FileSourceDto() @@ -180,20 +192,23 @@ public class ScmActionTest { .setSourceData(DbFileSources.Data.newBuilder().build())); dbSession.commit(); - WsTester.TestRequest request = tester.newGetRequest("api/sources", "scm").setParam("key", FILE_KEY); - request.execute().assertJson(getClass(), "return_empty_value_when_no_scm.json"); + tester.newRequest() + .setParam("key", FILE_KEY) + .execute() + .assertJson(getClass(), "return_empty_value_when_no_scm.json"); } @Test(expected = ForbiddenException.class) - public void fail_without_code_viewer_permission() throws Exception { + public void fail_without_code_viewer_permission() { userSessionRule.addProjectPermission(UserRole.USER, project, file); - WsTester.TestRequest request = tester.newGetRequest("api/sources", "scm").setParam("key", FILE_KEY); - request.execute(); + tester.newRequest() + .setParam("key", FILE_KEY) + .execute(); } @Test - public void fail_when_using_branch_db_key() throws Exception { + public void fail_when_using_branch_db_key() { ComponentDto project = dbTester.components().insertMainBranch(); ComponentDto branch = dbTester.components().insertProjectBranch(project); userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project); @@ -201,7 +216,7 @@ public class ScmActionTest { expectedException.expect(NotFoundException.class); expectedException.expectMessage(format("Component key '%s' not found", branch.getDbKey())); - tester.newGetRequest("api/sources", "scm") + tester.newRequest() .setParam("key", branch.getDbKey()) .execute(); } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/ShowActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/ShowActionTest.java index 7298346fe57..cbec2a0ebb1 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/ShowActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/ShowActionTest.java @@ -23,9 +23,6 @@ import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; import org.sonar.api.resources.Qualifiers; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; @@ -39,7 +36,7 @@ import org.sonar.server.component.ComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.source.SourceService; import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.ws.WsTester; +import org.sonar.server.ws.WsActionTester; import static com.google.common.collect.Lists.newArrayList; import static org.mockito.ArgumentMatchers.anyInt; @@ -48,38 +45,29 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) public class ShowActionTest { @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); - SourceService sourceService = mock(SourceService.class); - - WsTester tester; - - @Mock - DbClient dbClient; - - @Mock - DbSession session; - - @Mock - ComponentDao componentDao; - - ComponentDto project = ComponentTesting.newPrivateProjectDto(OrganizationTesting.newOrganizationDto()); - ComponentDto file = ComponentTesting.newFileDto(project, null); + private SourceService sourceService = mock(SourceService.class); + private DbClient dbClient = mock(DbClient.class); + private DbSession session = mock(DbSession.class); + private ComponentDao componentDao = mock(ComponentDao.class); + private ComponentDto project = ComponentTesting.newPrivateProjectDto(OrganizationTesting.newOrganizationDto()); + private ComponentDto file = ComponentTesting.newFileDto(project, null); + private ShowAction underTest = new ShowAction(sourceService, dbClient, userSessionRule, + new ComponentFinder(dbClient, new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT))); + private WsActionTester tester = new WsActionTester(underTest); @Before public void setUp() { when(dbClient.componentDao()).thenReturn(componentDao); when(dbClient.openSession(false)).thenReturn(session); - tester = new WsTester(new SourcesWs(new ShowAction(sourceService, dbClient, userSessionRule, - new ComponentFinder(dbClient, new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT))))); } @Test - public void show_source() throws Exception { + public void show_source() { String fileKey = "src/Foo.java"; userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project); when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.of(file)); @@ -91,12 +79,14 @@ public class ShowActionTest { "public class HelloWorld {", "}"))); - WsTester.TestRequest request = tester.newGetRequest("api/sources", "show").setParam("key", fileKey); - request.execute().assertJson(getClass(), "show_source.json"); + tester.newRequest() + .setParam("key", fileKey) + .execute() + .assertJson(getClass(), "show_source.json"); } @Test - public void show_source_with_from_and_to_params() throws Exception { + public void show_source_with_from_and_to_params() { String fileKey = "src/Foo.java"; userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project); when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.of(file)); @@ -104,16 +94,16 @@ public class ShowActionTest { " */", "", "public class HelloWorld {"))); - WsTester.TestRequest request = tester - .newGetRequest("api/sources", "show") + tester.newRequest() .setParam("key", fileKey) .setParam("from", "3") - .setParam("to", "5"); - request.execute().assertJson(getClass(), "show_source_with_params_from_and_to.json"); + .setParam("to", "5") + .execute() + .assertJson(getClass(), "show_source_with_params_from_and_to.json"); } @Test - public void show_source_accept_from_less_than_one() throws Exception { + public void show_source_accept_from_less_than_one() { String fileKey = "src/Foo.java"; userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project); when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.of(file)); @@ -121,19 +111,18 @@ public class ShowActionTest { " */", "", "public class HelloWorld {"))); - WsTester.TestRequest request = tester - .newGetRequest("api/sources", "show") + tester.newRequest() .setParam("key", fileKey) .setParam("from", "0") - .setParam("to", "5"); - request.execute(); + .setParam("to", "5") + .execute(); verify(sourceService).getLinesAsHtml(session, file.uuid(), 1, 5); } @Test(expected = ForbiddenException.class) - public void require_code_viewer() throws Exception { + public void require_code_viewer() { String fileKey = "src/Foo.java"; when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.of(file)); - tester.newGetRequest("api/sources", "show").setParam("key", fileKey).execute(); + tester.newRequest().setParam("key", fileKey).execute(); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/SourcesWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/SourcesWsTest.java index bc755b51893..c4f1bca367c 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/SourcesWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/SourcesWsTest.java @@ -25,7 +25,6 @@ import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.ws.WsTester; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; @@ -51,9 +50,12 @@ public class SourcesWsTest { }) .toArray(SourcesWsAction[]::new); - WsTester underTest = new WsTester(new SourcesWs(actions)); + SourcesWs underTest = new SourcesWs(actions); + WebService.Context context = new WebService.Context(); - WebService.Controller controller = underTest.controller("api/sources"); + underTest.define(context); + + WebService.Controller controller = context.controller("api/sources"); assertThat(controller).isNotNull(); assertThat(controller.since()).isEqualTo("4.2"); assertThat(controller.description()).isNotEmpty(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/updatecenter/ws/UpdateCenterWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/updatecenter/ws/UpdateCenterWsTest.java index f1ce9d80047..b0750eca5ae 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/updatecenter/ws/UpdateCenterWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/updatecenter/ws/UpdateCenterWsTest.java @@ -19,42 +19,36 @@ */ package org.sonar.server.updatecenter.ws; -import org.junit.Before; import org.junit.Test; +import org.sonar.api.server.ws.Request; +import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; -import org.sonar.server.platform.ServerFileSystem; -import org.sonar.server.ws.WsTester; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; public class UpdateCenterWsTest { + private UpdateCenterWs underTest = new UpdateCenterWs(new UpdateCenterWsAction() { + @Override + public void define(WebService.NewController context) { + context.createAction("foo").setHandler(this); + } - WsTester tester; + @Override + public void handle(Request request, Response response) { - @Before - public void setUp() { - tester = new WsTester(new UpdateCenterWs(new UploadAction(null, mock(ServerFileSystem.class)))); - } + } + }); @Test public void define_controller() { - WebService.Controller controller = tester.controller("api/updatecenter"); + WebService.Context context = new WebService.Context(); + + underTest.define(context); + + WebService.Controller controller = context.controller("api/updatecenter"); assertThat(controller).isNotNull(); assertThat(controller.since()).isEqualTo("2.10"); assertThat(controller.description()).isNotEmpty(); assertThat(controller.actions()).hasSize(1); } - - @Test - public void define_upload_action() { - WebService.Controller controller = tester.controller("api/updatecenter"); - - WebService.Action action = controller.action("upload"); - assertThat(action).isNotNull(); - assertThat(action.handler()).isNotNull(); - assertThat(action.isInternal()).isTrue(); - assertThat(action.isPost()).isTrue(); - assertThat(action.params()).hasSize(1); - } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/updatecenter/ws/UploadActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/updatecenter/ws/UploadActionTest.java index 92bb1e2bd64..6601f40de4f 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/updatecenter/ws/UploadActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/updatecenter/ws/UploadActionTest.java @@ -27,6 +27,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; +import org.sonar.api.server.ws.WebService; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.platform.ServerFileSystem; import org.sonar.server.tester.UserSessionRule; @@ -64,6 +65,18 @@ public class UploadActionTest { wsTester = new WsActionTester(new UploadAction(userSession, fileSystem)); } + @Test + public void define_upload_action() { + WebService.Action action = wsTester.getDef(); + + assertThat(action).isNotNull(); + assertThat(action.key()).isEqualTo("upload"); + assertThat(action.handler()).isNotNull(); + assertThat(action.isInternal()).isTrue(); + assertThat(action.isPost()).isTrue(); + assertThat(action.params()).hasSize(1); + } + @Test public void upload_plugin() throws Exception { logInAsSystemAdministrator(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/UserPropertiesWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/UserPropertiesWsTest.java index 59ca8b02538..b836057a4b9 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/UserPropertiesWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/UserPropertiesWsTest.java @@ -21,20 +21,30 @@ package org.sonar.server.user.ws; import org.junit.Test; import org.sonar.api.server.ws.WebService; -import org.sonar.server.ws.WsTester; +import org.sonar.server.ws.RemovedWebServiceHandler; import static org.assertj.core.api.Assertions.assertThat; public class UserPropertiesWsTest { - WsTester tester = new WsTester(new UserPropertiesWs()); + private UserPropertiesWs underTest = new UserPropertiesWs(); @Test public void define_ws() { - WebService.Controller controller = tester.controller("api/user_properties"); + WebService.Context context = new WebService.Context(); + + underTest.define(context); + + WebService.Controller controller = context.controller("api/user_properties"); assertThat(controller).isNotNull(); assertThat(controller.description()).isNotEmpty(); assertThat(controller.actions()).hasSize(1); + + WebService.Action index = controller.action("index"); + assertThat(index.since()).isEqualTo("2.6"); + assertThat(index.deprecatedSince()).isEqualTo("6.3"); + assertThat(index.handler()).isSameAs(RemovedWebServiceHandler.INSTANCE); + assertThat(index.responseExample()).isEqualTo(RemovedWebServiceHandler.INSTANCE.getResponseExample()); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/CreateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/CreateActionTest.java index 595d60907cc..1a45cc57a72 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/CreateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/CreateActionTest.java @@ -20,10 +20,10 @@ package org.sonar.server.usergroups.ws; import org.apache.commons.lang.StringUtils; -import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.organization.OrganizationDto; @@ -34,7 +34,7 @@ import org.sonar.server.organization.DefaultOrganization; import org.sonar.server.organization.TestDefaultOrganizationProvider; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.usergroups.DefaultGroupFinder; -import org.sonar.server.ws.WsTester; +import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.db.permission.OrganizationPermission.ADMINISTER; @@ -49,18 +49,24 @@ public class CreateActionTest { public ExpectedException expectedException = ExpectedException.none(); private TestDefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db); - private WsTester ws; + private CreateAction underTest = new CreateAction(db.getDbClient(), userSession, newGroupWsSupport()); + private WsActionTester tester = new WsActionTester(underTest); - @Before - public void setUp() { - ws = new WsTester(new UserGroupsWs(new CreateAction(db.getDbClient(), userSession, newGroupWsSupport()))); + @Test + public void define_create_action() { + WebService.Action action = tester.getDef(); + assertThat(action).isNotNull(); + assertThat(action.key()).isEqualTo("create"); + assertThat(action.isPost()).isTrue(); + assertThat(action.responseExampleAsString()).isNotEmpty(); + assertThat(action.params()).hasSize(3); } @Test - public void create_group_on_default_organization() throws Exception { + public void create_group_on_default_organization() { loginAsAdminOnDefaultOrganization(); - newRequest() + tester.newRequest() .setParam("name", "some-product-bu") .setParam("description", "Business Unit for Some Awesome Product") .execute() @@ -77,11 +83,11 @@ public class CreateActionTest { } @Test - public void create_group_on_specific_organization() throws Exception { + public void create_group_on_specific_organization() { OrganizationDto org = db.organizations().insert(); loginAsAdmin(org); - newRequest() + tester.newRequest() .setParam("organization", org.getKey()) .setParam("name", "some-product-bu") .setParam("description", "Business Unit for Some Awesome Product") @@ -101,10 +107,10 @@ public class CreateActionTest { } @Test - public void return_default_field() throws Exception { + public void return_default_field() { loginAsAdminOnDefaultOrganization(); - newRequest() + tester.newRequest() .setParam("name", "some-product-bu") .setParam("description", "Business Unit for Some Awesome Product") .execute() @@ -120,26 +126,26 @@ public class CreateActionTest { } @Test - public void fail_if_not_administrator() throws Exception { + public void fail_if_not_administrator() { userSession.logIn("not-admin"); expectedException.expect(ForbiddenException.class); - newRequest() + tester.newRequest() .setParam("name", "some-product-bu") .setParam("description", "Business Unit for Some Awesome Product") .execute(); } @Test - public void fail_if_administrator_of_another_organization() throws Exception { + public void fail_if_administrator_of_another_organization() { OrganizationDto org1 = db.organizations().insert(); OrganizationDto org2 = db.organizations().insert(); loginAsAdmin(org2); expectedException.expect(ForbiddenException.class); - newRequest() + tester.newRequest() .setParam("organization", org1.getKey()) .setParam("name", "some-product-bu") .setParam("description", "Business Unit for Some Awesome Product") @@ -147,44 +153,44 @@ public class CreateActionTest { } @Test(expected = IllegalArgumentException.class) - public void fail_if_name_is_too_short() throws Exception { + public void fail_if_name_is_too_short() { loginAsAdminOnDefaultOrganization(); - newRequest() + tester.newRequest() .setParam("name", "") .execute(); } @Test(expected = IllegalArgumentException.class) - public void fail_if_name_is_too_long() throws Exception { + public void fail_if_name_is_too_long() { loginAsAdminOnDefaultOrganization(); - newRequest() + tester.newRequest() .setParam("name", StringUtils.repeat("a", 255 + 1)) .execute(); } @Test(expected = IllegalArgumentException.class) - public void fail_if_name_is_anyone() throws Exception { + public void fail_if_name_is_anyone() { loginAsAdminOnDefaultOrganization(); - newRequest() + tester.newRequest() .setParam("name", "AnYoNe") .execute(); } @Test - public void fail_if_group_with_same_name_already_exists() throws Exception { + public void fail_if_group_with_same_name_already_exists() { GroupDto group = db.users().insertGroup(); loginAsAdminOnDefaultOrganization(); expectedException.expect(ServerException.class); expectedException.expectMessage("Group '" + group.getName() + "' already exists"); - newRequest() + tester.newRequest() .setParam("name", group.getName()) .execute(); } @Test - public void fail_if_group_with_same_name_already_exists_in_the_organization() throws Exception { + public void fail_if_group_with_same_name_already_exists_in_the_organization() { OrganizationDto org = db.organizations().insert(); GroupDto group = db.users().insertGroup(org, "the-group"); loginAsAdmin(org); @@ -192,21 +198,21 @@ public class CreateActionTest { expectedException.expect(ServerException.class); expectedException.expectMessage("Group '" + group.getName() + "' already exists"); - newRequest() + tester.newRequest() .setParam("organization", org.getKey()) .setParam("name", group.getName()) .execute(); } @Test - public void add_group_with_a_name_that_already_exists_in_another_organization() throws Exception { + public void add_group_with_a_name_that_already_exists_in_another_organization() { String name = "the-group"; OrganizationDto org1 = db.organizations().insert(); OrganizationDto org2 = db.organizations().insert(); GroupDto group = db.users().insertGroup(org1, name); loginAsAdmin(org2); - newRequest() + tester.newRequest() .setParam("organization", org2.getKey()) .setParam("name", name) .execute() @@ -222,18 +228,14 @@ public class CreateActionTest { } @Test(expected = IllegalArgumentException.class) - public void fail_if_description_is_too_long() throws Exception { + public void fail_if_description_is_too_long() { loginAsAdminOnDefaultOrganization(); - newRequest() + tester.newRequest() .setParam("name", "long-desc") .setParam("description", StringUtils.repeat("a", 1_000)) .execute(); } - private WsTester.TestRequest newRequest() { - return ws.newPostRequest("api/user_groups", "create"); - } - private void loginAsAdminOnDefaultOrganization() { loginAsAdmin(db.getDefaultOrganization()); } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/SearchActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/SearchActionTest.java index 364968d4e86..7bcdb9e3811 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/SearchActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/SearchActionTest.java @@ -64,6 +64,16 @@ public class SearchActionTest { private WsActionTester ws = new WsActionTester(new SearchAction(db.getDbClient(), userSession, newGroupWsSupport(), new DefaultGroupFinder(db.getDbClient()))); + + @Test + public void define_search_action() { + WebService.Action action = ws.getDef(); + assertThat(action).isNotNull(); + assertThat(action.key()).isEqualTo("search"); + assertThat(action.responseExampleAsString()).isNotEmpty(); + assertThat(action.params()).hasSize(5); + } + @Test public void search_without_parameters() { insertDefaultGroup(db.getDefaultOrganization(), "users", 0); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/UserGroupsWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/UserGroupsWsTest.java index 3cb634027b6..8066bd9ac1e 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/UserGroupsWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/UserGroupsWsTest.java @@ -19,57 +19,37 @@ */ package org.sonar.server.usergroups.ws; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; +import org.sonar.api.server.ws.Request; +import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; -import org.sonar.db.DbClient; -import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.user.UserSession; -import org.sonar.server.usergroups.DefaultGroupFinder; -import org.sonar.server.ws.WsTester; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; public class UserGroupsWsTest { - @Rule - public UserSessionRule userSessionRule = UserSessionRule.standalone(); + private UserGroupsWs underTest = new UserGroupsWs(new UserGroupsWsAction() { + @Override + public void define(WebService.NewController context) { + context.createAction("foo").setHandler(this); + } - WebService.Controller controller; + @Override + public void handle(Request request, Response response) { - @Before - public void setUp() { - GroupWsSupport wsSupport = mock(GroupWsSupport.class); - WsTester tester = new WsTester(new UserGroupsWs( - new SearchAction(mock(DbClient.class), mock(UserSession.class), wsSupport, mock(DefaultGroupFinder.class)), - new CreateAction(mock(DbClient.class), mock(UserSession.class), wsSupport))); - controller = tester.controller("api/user_groups"); - } + } + }); @Test public void define_controller() { + WebService.Context context = new WebService.Context(); + + underTest.define(context); + + WebService.Controller controller = context.controller("api/user_groups"); assertThat(controller).isNotNull(); assertThat(controller.description()).isNotEmpty(); assertThat(controller.since()).isEqualTo("5.2"); - assertThat(controller.actions()).hasSize(2); - } - - @Test - public void define_search_action() { - WebService.Action action = controller.action("search"); - assertThat(action).isNotNull(); - assertThat(action.responseExampleAsString()).isNotEmpty(); - assertThat(action.params()).hasSize(5); - } - - @Test - public void define_create_action() { - WebService.Action action = controller.action("create"); - assertThat(action).isNotNull(); - assertThat(action.isPost()).isTrue(); - assertThat(action.responseExampleAsString()).isNotEmpty(); - assertThat(action.params()).hasSize(3); + assertThat(controller.actions()).hasSize(1); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/GenerateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/GenerateActionTest.java index 0cf79cbca06..a55a07a9e56 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/GenerateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/GenerateActionTest.java @@ -24,6 +24,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.user.UserDto; @@ -69,6 +70,18 @@ public class GenerateActionTest { when(tokenGenerator.hash(anyString())).thenReturn("987654321"); } + @Test + public void generate_action() { + WebService.Action action = ws.getDef(); + + assertThat(action.key()).isEqualTo("generate"); + assertThat(action.since()).isEqualTo("5.3"); + assertThat(action.responseExampleAsString()).isNotEmpty(); + assertThat(action.isPost()).isTrue(); + assertThat(action.param("login").isRequired()).isFalse(); + assertThat(action.param("name").isRequired()).isTrue(); + } + @Test public void json_example() { UserDto user1 = db.users().insertUser(u -> u.setLogin("grace.hopper")); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/RevokeActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/RevokeActionTest.java index 40bfe2b105a..1f1118fd447 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/RevokeActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/RevokeActionTest.java @@ -23,6 +23,7 @@ import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbSession; @@ -53,6 +54,18 @@ public class RevokeActionTest { private DbSession dbSession = db.getSession(); private WsActionTester ws = new WsActionTester(new RevokeAction(dbClient, new UserTokenSupport(db.getDbClient(), userSession))); + @Test + public void revoke_action() { + WebService.Action action = ws.getDef(); + + assertThat(action).isNotNull(); + assertThat(action.key()).isEqualTo("revoke"); + assertThat(action.since()).isEqualTo("5.3"); + assertThat(action.isPost()).isTrue(); + assertThat(action.param("login").isRequired()).isFalse(); + assertThat(action.param("name").isRequired()).isTrue(); + } + @Test public void delete_token_in_db() { logInAsSystemAdministrator(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/SearchActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/SearchActionTest.java index c562e70fa4b..225eeef5fea 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/SearchActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/SearchActionTest.java @@ -23,6 +23,7 @@ import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbTester; @@ -55,6 +56,17 @@ public class SearchActionTest { private DbClient dbClient = db.getDbClient(); private WsActionTester ws = new WsActionTester(new SearchAction(dbClient, new UserTokenSupport(db.getDbClient(), userSession))); + @Test + public void search_action() { + WebService.Action action = ws.getDef(); + + assertThat(action).isNotNull(); + assertThat(action.key()).isEqualTo("search"); + assertThat(action.since()).isEqualTo("5.3"); + assertThat(action.isPost()).isFalse(); + assertThat(action.param("login").isRequired()).isFalse(); + } + @Test public void search_json_example() { UserDto user1 = db.users().insertUser(u -> u.setLogin("grace.hopper")); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/UserTokensWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/UserTokensWsTest.java index ab80b3ec8aa..439e85b386a 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/UserTokensWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/UserTokensWsTest.java @@ -19,65 +19,37 @@ */ package org.sonar.server.usertoken.ws; -import org.junit.Before; import org.junit.Test; +import org.sonar.api.server.ws.Request; +import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; -import org.sonar.api.utils.System2; -import org.sonar.db.DbClient; -import org.sonar.server.usertoken.TokenGenerator; -import org.sonar.server.ws.WsTester; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; public class UserTokensWsTest { - static final String CONTROLLER_KEY = "api/user_tokens"; - WsTester ws; + private UserTokensWs underTest = new UserTokensWs(new UserTokensWsAction() { + @Override + public void define(WebService.NewController context) { + context.createAction("foo").setHandler(this); + } - @Before - public void setUp() { - DbClient dbClient = mock(DbClient.class); - System2 system = mock(System2.class); - TokenGenerator tokenGenerator = mock(TokenGenerator.class); - UserTokenSupport userTokenSupport = mock(UserTokenSupport.class); + @Override + public void handle(Request request, Response response) { - ws = new WsTester(new UserTokensWs( - new GenerateAction(dbClient, system, tokenGenerator, userTokenSupport), - new RevokeAction(dbClient, userTokenSupport), - new SearchAction(dbClient, userTokenSupport))); - } - - @Test - public void generate_action() { - WebService.Action action = ws.action(CONTROLLER_KEY, "generate"); - - assertThat(action).isNotNull(); - assertThat(action.since()).isEqualTo("5.3"); - assertThat(action.responseExampleAsString()).isNotEmpty(); - assertThat(action.isPost()).isTrue(); - assertThat(action.param("login").isRequired()).isFalse(); - assertThat(action.param("name").isRequired()).isTrue(); - } + } + }); @Test - public void revoke_action() { - WebService.Action action = ws.action(CONTROLLER_KEY, "revoke"); - - assertThat(action).isNotNull(); - assertThat(action.since()).isEqualTo("5.3"); - assertThat(action.isPost()).isTrue(); - assertThat(action.param("login").isRequired()).isFalse(); - assertThat(action.param("name").isRequired()).isTrue(); - } + public void is_defined() { + WebService.Context context = new WebService.Context(); - @Test - public void search_action() { - WebService.Action action = ws.action(CONTROLLER_KEY, "search"); + underTest.define(context); - assertThat(action).isNotNull(); - assertThat(action.since()).isEqualTo("5.3"); - assertThat(action.isPost()).isFalse(); - assertThat(action.param("login").isRequired()).isFalse(); + WebService.Controller controller = context.controller("api/user_tokens"); + assertThat(controller).isNotNull(); + assertThat(controller.since()).isEqualTo("5.3"); + assertThat(controller.description()).isNotEmpty(); + assertThat(controller.actions()).hasSize(1); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ws/ws/ListActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ws/ws/ListActionTest.java new file mode 100644 index 00000000000..f118e8b99f9 --- /dev/null +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ws/ws/ListActionTest.java @@ -0,0 +1,76 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.server.ws.ws; + +import java.util.Arrays; +import org.junit.Before; +import org.junit.Test; +import org.sonar.api.server.ws.WebService; +import org.sonar.server.ws.TestRequest; + +import static org.sonar.test.JsonAssert.assertJson; + +public class ListActionTest { + private WebService.Context context = new WebService.Context(); + private ListAction underTest = new ListAction(); + private WebService.Action action; + + @Before + public void setUp() throws Exception { + WebService.NewController newController = context.createController("api/webservices") + .setDescription("Get information on the web api supported on this instance.") + .setSince("4.2"); + + for (WebServicesWsAction wsWsAction : Arrays.asList(underTest, new ResponseExampleAction())) { + wsWsAction.define(newController); + wsWsAction.setContext(context); + } + + newController.done(); + action = context.controller("api/webservices").action("list"); + } + + @Test + public void list() { + new MetricWs().define(context); + + String response = newRequest().execute().getInput(); + + assertJson(response).withStrictArrayOrder().isSimilarTo(getClass().getResource("list-example.json")); + } + + @Test + public void list_including_internals() { + MetricWs metricWs = new MetricWs(); + metricWs.define(context); + + newRequest() + .setParam("include_internals", "true") + .execute() + .assertJson(getClass(), "list_including_internals.json"); + } + + public TestRequest newRequest() { + TestRequest request = new TestRequest(); + request.setAction(action); + return request; + } + +} diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ws/ws/MetricWs.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ws/ws/MetricWs.java new file mode 100644 index 00000000000..8dfbe21193d --- /dev/null +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ws/ws/MetricWs.java @@ -0,0 +1,88 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.server.ws.ws; + +import com.google.common.io.Resources; +import org.sonar.api.server.ws.Change; +import org.sonar.api.server.ws.WebService; + +class MetricWs implements WebService { + @Override + public void define(Context context) { + NewController newController = context + .createController("api/metric") + .setDescription("Metrics") + .setSince("3.2"); + + // action with default values + newController.createAction("show") + .setSince("3.2") + .setDescription("Show Description") + .setResponseExample(getClass().getResource("web-services-ws-test.txt")) + .setHandler((request, response) -> { + }); + + // action with a lot of overridden values + NewAction create = newController.createAction("create") + .setPost(true) + .setDescription("Create metric") + .setSince("4.1") + .setDeprecatedSince("5.3") + .setResponseExample(Resources.getResource(getClass(), "ListActionTest/metrics_example.json")) + .setChangelog( + new Change("4.5", "Deprecate database ID in response"), + new Change("6.0", "Remove database ID from response"), + new Change("6.6", "Requires 'Administer System' permission instead of 'Administer Quality Profiles'")) + .setHandler((request, response) -> { + }); + + create + .createParam("severity") + .setDescription("Severity") + .setSince("4.4") + .setDeprecatedSince("5.2") + .setDeprecatedKey("old_severity", "4.6") + .setRequired(false) + .setPossibleValues("BLOCKER", "INFO") + .setExampleValue("INFO") + .setDefaultValue("BLOCKER"); + create.createParam("name"); + create.createParam("internal").setInternal(true); + + create + .createParam("constrained_string_param") + .setMaximumLength(64) + .setMinimumLength(3); + + create + .createParam("constrained_numeric_param") + .setMaximumValue(12); + + newController.createAction("internal_action") + .setDescription("Internal Action Description") + .setResponseExample(getClass().getResource("web-services-ws-test.txt")) + .setSince("5.3") + .setInternal(true) + .setHandler((request, response) -> { + }); + + newController.done(); + } +} diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ws/ws/ResponseExampleActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ws/ws/ResponseExampleActionTest.java new file mode 100644 index 00000000000..a5a389280f9 --- /dev/null +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ws/ws/ResponseExampleActionTest.java @@ -0,0 +1,60 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.server.ws.ws; + +import com.google.common.collect.Iterables; +import org.junit.Before; +import org.junit.Test; +import org.sonar.api.server.ws.WebService; +import org.sonar.server.ws.TestRequest; + +public class ResponseExampleActionTest { + private WebService.Context context = new WebService.Context(); + private ResponseExampleAction underTest = new ResponseExampleAction(); + private WebService.Action action; + + @Before + public void setUp() throws Exception { + WebService.NewController newController = context.createController("api/ws"); + underTest.define(newController); + newController.done(); + action = Iterables.get(context.controller("api/ws").actions(), 0); + underTest.setContext(context); + } + + @Test + public void response_example() { + MetricWs metricWs = new MetricWs(); + metricWs.define(context); + + newRequest() + .setParam("controller", "api/metric") + .setParam("action", "create") + .execute() + .assertJson(getClass(), "response_example.json"); + } + + public TestRequest newRequest() { + TestRequest request = new TestRequest(); + request.setAction(action); + return request; + } + +} diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ws/ws/WebServicesWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ws/ws/WebServicesWsTest.java index 75b83c03e13..b442c6dafaa 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ws/ws/WebServicesWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ws/ws/WebServicesWsTest.java @@ -19,130 +19,52 @@ */ package org.sonar.server.ws.ws; -import com.google.common.io.Resources; +import java.util.Arrays; import org.junit.Test; -import org.sonar.api.server.ws.Change; +import org.sonar.api.server.ws.Request; +import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; -import org.sonar.server.ws.WsTester; -import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; -import static org.sonar.test.JsonAssert.assertJson; public class WebServicesWsTest { - private WebServicesWs underTest = new WebServicesWs(asList(new ListAction(), new ResponseExampleAction())); + private DummyWebServicesWsAction dummyWebServicesWsAction = new DummyWebServicesWsAction(); + private WebServicesWs underTest = new WebServicesWs(Arrays.asList(dummyWebServicesWsAction)); @Test public void define_ws() { - WsTester tester = new WsTester(underTest); - WebService.Controller controller = tester.controller("api/webservices"); + WebService.Context context = new WebService.Context(); + + underTest.define(context); + + WebService.Controller controller = context.controller("api/webservices"); assertThat(controller).isNotNull(); assertThat(controller.path()).isEqualTo("api/webservices"); assertThat(controller.since()).isEqualTo("4.2"); assertThat(controller.description()).isNotEmpty(); - assertThat(controller.actions()).hasSize(2); - - WebService.Action index = controller.action("list"); - assertThat(index).isNotNull(); - assertThat(index.key()).isEqualTo("list"); - assertThat(index.handler()).isNotNull(); - assertThat(index.since()).isEqualTo("4.2"); - assertThat(index.isPost()).isFalse(); - assertThat(index.isInternal()).isFalse(); - - assertThat(controller.action("response_example")).isNotNull(); - } + assertThat(controller.actions()).hasSize(1); - @Test - public void list() throws Exception { - WsTester tester = new WsTester(underTest, new MetricWs()); - - String response = tester.newGetRequest("api/webservices", "list").execute().outputAsString(); - - assertJson(response).withStrictArrayOrder().isSimilarTo(getClass().getResource("list-example.json")); + assertThat(dummyWebServicesWsAction.context).isNotNull(); } - @Test - public void list_including_internals() throws Exception { - WsTester tester = new WsTester(underTest, new MetricWs()); - tester.newGetRequest("api/webservices", "list") - .setParam("include_internals", "true") - .execute() - .assertJson(getClass(), "list_including_internals.json"); - } + private static class DummyWebServicesWsAction implements WebServicesWsAction { - @Test - public void response_example() throws Exception { - WsTester tester = new WsTester(underTest, new MetricWs()); - tester - .newGetRequest("api/webservices", "response_example") - .setParam("controller", "api/metric") - .setParam("action", "create") - .execute().assertJson(getClass(), "response_example.json"); - } + private WebService.Context context; - private static class MetricWs implements WebService { @Override - public void define(Context context) { - NewController newController = context - .createController("api/metric") - .setDescription("Metrics") - .setSince("3.2"); - - // action with default values - newController.createAction("show") - .setSince("3.2") - .setDescription("Show Description") - .setResponseExample(getClass().getResource("web-services-ws-test.txt")) - .setHandler((request, response) -> { - }); - - // action with a lot of overridden values - NewAction create = newController.createAction("create") - .setPost(true) - .setDescription("Create metric") - .setSince("4.1") - .setDeprecatedSince("5.3") - .setResponseExample(Resources.getResource(getClass(), "WebServicesWsTest/metrics_example.json")) - .setChangelog( - new Change("4.5", "Deprecate database ID in response"), - new Change("6.0", "Remove database ID from response"), - new Change("6.6", "Requires 'Administer System' permission instead of 'Administer Quality Profiles'")) - .setHandler((request, response) -> { - }); - - create - .createParam("severity") - .setDescription("Severity") - .setSince("4.4") - .setDeprecatedSince("5.2") - .setDeprecatedKey("old_severity", "4.6") - .setRequired(false) - .setPossibleValues("BLOCKER", "INFO") - .setExampleValue("INFO") - .setDefaultValue("BLOCKER"); - create.createParam("name"); - create.createParam("internal").setInternal(true); - - create - .createParam("constrained_string_param") - .setMaximumLength(64) - .setMinimumLength(3); + public void setContext(WebService.Context context) { + this.context = context; + } - create - .createParam("constrained_numeric_param") - .setMaximumValue(12); + @Override + public void define(WebService.NewController context) { + context.createAction("foo").setHandler(this); + } - newController.createAction("internal_action") - .setDescription("Internal Action Description") - .setResponseExample(getClass().getResource("web-services-ws-test.txt")) - .setSince("5.3") - .setInternal(true) - .setHandler((request, response) -> { - }); + @Override + public void handle(Request request, Response response) { - newController.done(); } } } diff --git a/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/LanguageWsTest/list.json b/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/LanguageWsTest/list.json deleted file mode 100644 index 32190c0008f..00000000000 --- a/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/LanguageWsTest/list.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "languages": [ - {"key": "ac", "name": "ArnoldC"}, - {"key": "lol", "name": "LOLCODE"}, - {"key": "ook", "name": "Ook!"}, - {"key": "ws", "name": "Whitespace"} - ] -} diff --git a/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/LanguageWsTest/list_filtered_key.json b/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/LanguageWsTest/list_filtered_key.json deleted file mode 100644 index 187ce02ada0..00000000000 --- a/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/LanguageWsTest/list_filtered_key.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "languages": [ - {"key": "ws", "name": "Whitespace"} - ] -} diff --git a/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/LanguageWsTest/list_filtered_name.json b/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/LanguageWsTest/list_filtered_name.json deleted file mode 100644 index 9f167f6f77e..00000000000 --- a/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/LanguageWsTest/list_filtered_name.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "languages": [ - {"key": "ac", "name": "ArnoldC"}, - {"key": "lol", "name": "LOLCODE"}, - {"key": "ook", "name": "Ook!"} - ] -} diff --git a/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/LanguageWsTest/list_limited.json b/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/LanguageWsTest/list_limited.json deleted file mode 100644 index 513d8b14de4..00000000000 --- a/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/LanguageWsTest/list_limited.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "languages": [ - {"key": "ac", "name": "ArnoldC"}, - {"key": "lol", "name": "LOLCODE"} - ] -} diff --git a/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/ListActionTest/list.json b/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/ListActionTest/list.json new file mode 100644 index 00000000000..32190c0008f --- /dev/null +++ b/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/ListActionTest/list.json @@ -0,0 +1,8 @@ +{ + "languages": [ + {"key": "ac", "name": "ArnoldC"}, + {"key": "lol", "name": "LOLCODE"}, + {"key": "ook", "name": "Ook!"}, + {"key": "ws", "name": "Whitespace"} + ] +} diff --git a/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/ListActionTest/list_filtered_key.json b/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/ListActionTest/list_filtered_key.json new file mode 100644 index 00000000000..187ce02ada0 --- /dev/null +++ b/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/ListActionTest/list_filtered_key.json @@ -0,0 +1,5 @@ +{ + "languages": [ + {"key": "ws", "name": "Whitespace"} + ] +} diff --git a/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/ListActionTest/list_filtered_name.json b/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/ListActionTest/list_filtered_name.json new file mode 100644 index 00000000000..9f167f6f77e --- /dev/null +++ b/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/ListActionTest/list_filtered_name.json @@ -0,0 +1,7 @@ +{ + "languages": [ + {"key": "ac", "name": "ArnoldC"}, + {"key": "lol", "name": "LOLCODE"}, + {"key": "ook", "name": "Ook!"} + ] +} diff --git a/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/ListActionTest/list_limited.json b/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/ListActionTest/list_limited.json new file mode 100644 index 00000000000..513d8b14de4 --- /dev/null +++ b/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/language/ws/ListActionTest/list_limited.json @@ -0,0 +1,6 @@ +{ + "languages": [ + {"key": "ac", "name": "ArnoldC"}, + {"key": "lol", "name": "LOLCODE"} + ] +} diff --git a/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/ws/ws/ListActionTest/list_including_internals.json b/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/ws/ws/ListActionTest/list_including_internals.json new file mode 100644 index 00000000000..d118e6e60cf --- /dev/null +++ b/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/ws/ws/ListActionTest/list_including_internals.json @@ -0,0 +1,124 @@ +{ + "webServices": [ + { + "path": "api/metric", + "since": "3.2", + "description": "Metrics", + "actions": [ + { + "key": "create", + "description": "Create metric", + "since": "4.1", + "internal": false, + "post": true, + "hasResponseExample": true, + "params": [ + { + "key": "constrained_numeric_param", + "required": false, + "internal": false, + "maximumValue": 12 + }, + { + "key": "constrained_string_param", + "required": false, + "internal": false, + "maximumLength": 64, + "minimumLength": 3 + }, + { + "key": "name", + "required": false, + "internal": false + }, + { + "key": "severity", + "description": "Severity", + "required": false, + "internal": false, + "defaultValue": "BLOCKER", + "exampleValue": "INFO", + "possibleValues": [ + "BLOCKER", + "INFO" + ] + }, + { + "key": "internal", + "required": false, + "internal": true + } + ] + }, + { + "key": "internal_action", + "since": "5.3", + "internal": true, + "post": false, + "hasResponseExample": true + }, + { + "key": "show", + "since": "3.2", + "internal": false, + "post": false, + "hasResponseExample": true + } + ] + }, + { + "path": "api/webservices", + "description": "Get information on the web api supported on this instance.", + "since": "4.2", + "actions": [ + { + "key": "list", + "since": "4.2", + "description": "List web services", + "internal": false, + "post": false, + "hasResponseExample": true, + "params": [ + { + "key": "include_internals", + "description": "Include web services that are implemented for internal use only. Their forward-compatibility is not assured", + "required": false, + "internal": false, + "defaultValue": "false", + "possibleValues": [ + "true", + "false", + "yes", + "no" + ] + } + ] + }, + { + "key": "response_example", + "since": "4.4", + "description": "Display web service response example", + "internal": false, + "post": false, + "hasResponseExample": true, + "params": [ + { + "key": "action", + "required": true, + "internal": false, + "description": "Action of the web service", + "exampleValue": "search" + }, + { + "key": "controller", + "required": true, + "internal": false, + "description": "Controller of the web service", + "exampleValue": "api/issues" + } + ] + } + ] + } + ] +} diff --git a/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/ws/ws/ListActionTest/metrics_example.json b/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/ws/ws/ListActionTest/metrics_example.json new file mode 100644 index 00000000000..2516f68de60 --- /dev/null +++ b/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/ws/ws/ListActionTest/metrics_example.json @@ -0,0 +1 @@ +{"metrics":[]} diff --git a/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/ws/ws/ResponseExampleActionTest/response_example.json b/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/ws/ws/ResponseExampleActionTest/response_example.json new file mode 100644 index 00000000000..1b37618babd --- /dev/null +++ b/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/ws/ws/ResponseExampleActionTest/response_example.json @@ -0,0 +1 @@ +{"format":"json","example":"{\"metrics\":[]}"} diff --git a/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/ws/ws/WebServicesWsTest/list_including_internals.json b/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/ws/ws/WebServicesWsTest/list_including_internals.json deleted file mode 100644 index d118e6e60cf..00000000000 --- a/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/ws/ws/WebServicesWsTest/list_including_internals.json +++ /dev/null @@ -1,124 +0,0 @@ -{ - "webServices": [ - { - "path": "api/metric", - "since": "3.2", - "description": "Metrics", - "actions": [ - { - "key": "create", - "description": "Create metric", - "since": "4.1", - "internal": false, - "post": true, - "hasResponseExample": true, - "params": [ - { - "key": "constrained_numeric_param", - "required": false, - "internal": false, - "maximumValue": 12 - }, - { - "key": "constrained_string_param", - "required": false, - "internal": false, - "maximumLength": 64, - "minimumLength": 3 - }, - { - "key": "name", - "required": false, - "internal": false - }, - { - "key": "severity", - "description": "Severity", - "required": false, - "internal": false, - "defaultValue": "BLOCKER", - "exampleValue": "INFO", - "possibleValues": [ - "BLOCKER", - "INFO" - ] - }, - { - "key": "internal", - "required": false, - "internal": true - } - ] - }, - { - "key": "internal_action", - "since": "5.3", - "internal": true, - "post": false, - "hasResponseExample": true - }, - { - "key": "show", - "since": "3.2", - "internal": false, - "post": false, - "hasResponseExample": true - } - ] - }, - { - "path": "api/webservices", - "description": "Get information on the web api supported on this instance.", - "since": "4.2", - "actions": [ - { - "key": "list", - "since": "4.2", - "description": "List web services", - "internal": false, - "post": false, - "hasResponseExample": true, - "params": [ - { - "key": "include_internals", - "description": "Include web services that are implemented for internal use only. Their forward-compatibility is not assured", - "required": false, - "internal": false, - "defaultValue": "false", - "possibleValues": [ - "true", - "false", - "yes", - "no" - ] - } - ] - }, - { - "key": "response_example", - "since": "4.4", - "description": "Display web service response example", - "internal": false, - "post": false, - "hasResponseExample": true, - "params": [ - { - "key": "action", - "required": true, - "internal": false, - "description": "Action of the web service", - "exampleValue": "search" - }, - { - "key": "controller", - "required": true, - "internal": false, - "description": "Controller of the web service", - "exampleValue": "api/issues" - } - ] - } - ] - } - ] -} diff --git a/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/ws/ws/WebServicesWsTest/metrics_example.json b/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/ws/ws/WebServicesWsTest/metrics_example.json deleted file mode 100644 index 2516f68de60..00000000000 --- a/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/ws/ws/WebServicesWsTest/metrics_example.json +++ /dev/null @@ -1 +0,0 @@ -{"metrics":[]} diff --git a/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/ws/ws/WebServicesWsTest/response_example.json b/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/ws/ws/WebServicesWsTest/response_example.json deleted file mode 100644 index 1b37618babd..00000000000 --- a/server/sonar-webserver-webapi/src/test/resources/org/sonar/server/ws/ws/WebServicesWsTest/response_example.json +++ /dev/null @@ -1 +0,0 @@ -{"format":"json","example":"{\"metrics\":[]}"} diff --git a/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/TestResponse.java b/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/TestResponse.java index 82057f06af0..352d0bb135d 100644 --- a/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/TestResponse.java +++ b/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/TestResponse.java @@ -23,16 +23,19 @@ import com.google.protobuf.GeneratedMessageV3; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.lang.reflect.Method; +import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import javax.annotation.CheckForNull; import org.sonar.test.JsonAssert; +import static org.assertj.core.api.Assertions.assertThat; + public class TestResponse { private final DumbResponse dumbResponse; - TestResponse(DumbResponse dumbResponse) { + public TestResponse(DumbResponse dumbResponse) { this.dumbResponse = dumbResponse; } @@ -88,4 +91,8 @@ public class TestResponse { } JsonAssert.assertJson(getInput()).isSimilarTo(url); } + + public void assertNoContent() { + assertThat(getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT); + } } diff --git a/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/WsTester.java b/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/WsTester.java deleted file mode 100644 index e69153b5033..00000000000 --- a/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/WsTester.java +++ /dev/null @@ -1,361 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.ws; - -import com.google.common.collect.Maps; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.net.HttpURLConnection; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.commons.io.IOUtils; -import org.sonar.api.server.ws.Response; -import org.sonar.api.server.ws.WebService; -import org.sonar.api.impl.ws.PartImpl; -import org.sonar.api.impl.ws.ValidatingRequest; -import org.sonar.api.utils.text.JsonWriter; -import org.sonar.api.utils.text.XmlWriter; -import org.sonar.server.ws.WsTester.TestResponse.TestStream; -import org.sonar.test.JsonAssert; -import org.sonarqube.ws.MediaTypes; - -import static java.util.Collections.emptyList; -import static java.util.Collections.singletonList; -import static java.util.Objects.requireNonNull; -import static org.assertj.core.api.Assertions.assertThat; -import static org.sonar.server.ws.RequestVerifier.verifyRequest; - -/** - * @since 4.2 - * @deprecated use {@link WsActionTester} in preference to this class - */ -@Deprecated -public class WsTester { - - public static class TestRequest extends ValidatingRequest { - - private final String method; - private String path; - private String mediaType = MediaTypes.JSON; - - private Map params = Maps.newHashMap(); - private Map headers = Maps.newHashMap(); - private final Map parts = Maps.newHashMap(); - - private TestRequest(String method) { - this.method = method; - } - - @Override - public String method() { - return method; - } - - @Override - public String getMediaType() { - return mediaType; - } - - public TestRequest setMediaType(String s) { - this.mediaType = s; - return this; - } - - @Override - public boolean hasParam(String key) { - return params.keySet().contains(key); - } - - @Override - public Optional header(String name) { - return Optional.ofNullable(headers.get(name)); - } - - public TestRequest setHeader(String name, String value) { - this.headers.put(requireNonNull(name), requireNonNull(value)); - return this; - } - - @Override - public String getPath() { - return path; - } - - public TestRequest setPath(String path) { - this.path = path; - return this; - } - - public TestRequest setParams(Map m) { - this.params = m; - return this; - } - - public TestRequest setParam(String key, @Nullable String value) { - if (value != null) { - params.put(key, value); - } - return this; - } - - @Override - protected String readParam(String key) { - return params.get(key); - } - - @Override - protected List readMultiParam(String key) { - String value = params.get(key); - return value == null ? emptyList() : singletonList(value); - } - - @Override - public Map getParams() { - return params.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new String[] {e.getValue()})); - } - - @Override - protected InputStream readInputStreamParam(String key) { - String param = readParam(key); - - return param == null ? null : IOUtils.toInputStream(param); - } - - @Override - protected Part readPart(String key) { - return parts.get(key); - } - - public TestRequest setPart(String key, InputStream input, String fileName) { - parts.put(key, new PartImpl(input, fileName)); - return this; - } - - public Result execute() throws Exception { - TestResponse response = new TestResponse(); - verifyRequest(action(), this); - action().handler().handle(this, response); - return new Result(response); - } - } - - public static class TestResponse implements Response { - - private TestStream stream; - - private Map headers = Maps.newHashMap(); - - public class TestStream implements Response.Stream { - private String mediaType; - private int status; - - @CheckForNull - public String mediaType() { - return mediaType; - } - - public int status() { - return status; - } - - @Override - public Response.Stream setMediaType(String s) { - this.mediaType = s; - return this; - } - - @Override - public Response.Stream setStatus(int i) { - this.status = i; - return this; - } - - @Override - public OutputStream output() { - return output; - } - } - - private final ByteArrayOutputStream output = new ByteArrayOutputStream(); - - @Override - public JsonWriter newJsonWriter() { - return JsonWriter.of(new OutputStreamWriter(output, StandardCharsets.UTF_8)); - } - - @Override - public XmlWriter newXmlWriter() { - return XmlWriter.of(new OutputStreamWriter(output, StandardCharsets.UTF_8)); - } - - @Override - public Stream stream() { - if (stream == null) { - stream = new TestStream(); - } - return stream; - } - - @Override - public Response noContent() { - stream().setStatus(HttpURLConnection.HTTP_NO_CONTENT); - IOUtils.closeQuietly(output); - return this; - } - - public String outputAsString() { - return new String(output.toByteArray(), StandardCharsets.UTF_8); - } - - @Override - public Response setHeader(String name, String value) { - headers.put(name, value); - return this; - } - - @Override - public Collection getHeaderNames() { - return headers.keySet(); - } - - @Override - public String getHeader(String name) { - return headers.get(name); - } - } - - public static class Result { - private final TestResponse response; - - private Result(TestResponse response) { - this.response = response; - } - - public Result assertNoContent() { - return assertStatus(HttpURLConnection.HTTP_NO_CONTENT); - } - - public String outputAsString() { - return new String(response.output.toByteArray(), StandardCharsets.UTF_8); - } - - public byte[] output() { - return response.output.toByteArray(); - } - - public Result assertJson(String expectedJson) { - String json = outputAsString(); - JsonAssert.assertJson(json).isSimilarTo(expectedJson); - return this; - } - - /** - * Compares JSON response with JSON file available in classpath. For example if class - * is org.foo.BarTest and filename is index.json, then file must be located - * at src/test/resources/org/foo/BarTest/index.json. - * - * @param clazz the test class - * @param expectedJsonFilename name of the file containing the expected JSON - */ - public Result assertJson(Class clazz, String expectedJsonFilename) { - String path = clazz.getSimpleName() + "/" + expectedJsonFilename; - URL url = clazz.getResource(path); - if (url == null) { - throw new IllegalStateException("Cannot find " + path); - } - String json = outputAsString(); - JsonAssert.assertJson(json).isSimilarTo(url); - return this; - } - - public Result assertNotModified() { - return assertStatus(HttpURLConnection.HTTP_NOT_MODIFIED); - } - - public Result assertStatus(int httpStatus) { - assertThat(((TestStream) response.stream()).status()).isEqualTo(httpStatus); - return this; - } - - public Result assertHeader(String name, String value) { - assertThat(response.getHeader(name)).isEqualTo(value); - return this; - } - } - - private final WebService.Context context = new WebService.Context(); - - public WsTester(WebService... webServices) { - for (WebService webService : webServices) { - webService.define(context); - } - } - - public WebService.Context context() { - return context; - } - - @CheckForNull - public WebService.Controller controller(String key) { - return context.controller(key); - } - - @CheckForNull - public WebService.Action action(String controllerKey, String actionKey) { - WebService.Controller controller = context.controller(controllerKey); - if (controller != null) { - return controller.action(actionKey); - } - return null; - } - - public TestRequest newGetRequest(String controllerKey, String actionKey) { - return newRequest(controllerKey, actionKey, "GET"); - } - - public TestRequest newPostRequest(String controllerKey, String actionKey) { - return newRequest(controllerKey, actionKey, "POST"); - } - - private TestRequest newRequest(String controllerKey, String actionKey, String method) { - TestRequest request = new TestRequest(method); - WebService.Controller controller = context.controller(controllerKey); - if (controller == null) { - throw new IllegalArgumentException( - String.format("Controller '%s' is unknown, did you forget to call NewController.done()?", controllerKey)); - } - WebService.Action action = controller.action(actionKey); - if (action == null) { - throw new IllegalArgumentException( - String.format("Action '%s' not found on controller '%s'.", actionKey, controllerKey)); - } - request.setAction(action); - return request; - } -}