]> source.dussan.org Git - sonarqube.git/commitdiff
Improve integration tests by using new Tester class
authorSimon Brandhof <simon.brandhof@sonarsource.com>
Thu, 15 Jun 2017 14:39:47 +0000 (16:39 +0200)
committerSimon Brandhof <simon.brandhof@sonarsource.com>
Fri, 23 Jun 2017 17:07:48 +0000 (19:07 +0200)
92 files changed:
cix.sh
it/it-tests/src/test/java/it/Category4Suite.java
it/it-tests/src/test/java/it/Category5Suite.java
it/it-tests/src/test/java/it/administration/ProjectsAdministrationTest.java
it/it-tests/src/test/java/it/issue/IssueCreationDateTest.java
it/it-tests/src/test/java/it/issue/IssueTagsTest.java
it/it-tests/src/test/java/it/issue/IssuesPageTest.java
it/it-tests/src/test/java/it/issue/OrganizationIssueAssignTest.java
it/it-tests/src/test/java/it/lite/LiteTest.java
it/it-tests/src/test/java/it/measure/ProjectDashboardTest.java
it/it-tests/src/test/java/it/measure/ProjectMeasuresPageTest.java
it/it-tests/src/test/java/it/measureHistory/DifferentialPeriodsTest.java
it/it-tests/src/test/java/it/organization/BillingTest.java
it/it-tests/src/test/java/it/organization/OrganizationMembershipTest.java
it/it-tests/src/test/java/it/organization/OrganizationMembershipUiTest.java
it/it-tests/src/test/java/it/organization/OrganizationTest.java
it/it-tests/src/test/java/it/organization/PersonalOrganizationTest.java
it/it-tests/src/test/java/it/organization/RootUserOnOrganizationTest.java
it/it-tests/src/test/java/it/organization/RootUserTest.java
it/it-tests/src/test/java/it/projectAdministration/BackgroundTasksTest.java
it/it-tests/src/test/java/it/projectAdministration/ProjectAdministrationTest.java
it/it-tests/src/test/java/it/projectAdministration/ProjectKeyPageTest.java
it/it-tests/src/test/java/it/projectAdministration/ProjectLinksPageTest.java
it/it-tests/src/test/java/it/projectAdministration/ProjectPermissionsTest.java
it/it-tests/src/test/java/it/projectAdministration/ProjectQualityGatePageTest.java
it/it-tests/src/test/java/it/projectEvent/ProjectActivityPageTest.java
it/it-tests/src/test/java/it/projectSearch/LeakProjectsPageTest.java
it/it-tests/src/test/java/it/projectSearch/ProjectsPageTest.java
it/it-tests/src/test/java/it/projectSearch/SearchProjectsTest.java
it/it-tests/src/test/java/it/qualityGate/QualityGateUiTest.java
it/it-tests/src/test/java/it/qualityProfile/BuiltInQualityProfilesTest.java
it/it-tests/src/test/java/it/qualityProfile/CustomQualityProfilesTest.java
it/it-tests/src/test/java/it/qualityProfile/OrganizationQualityProfilesUiTest.java
it/it-tests/src/test/java/it/qualityProfile/QualityProfilesUiTest.java
it/it-tests/src/test/java/it/rule/RuleTagsTest.java
it/it-tests/src/test/java/it/serverSystem/ClusterTest.java
it/it-tests/src/test/java/it/serverSystem/ServerSystemTest.java
it/it-tests/src/test/java/it/settings/DeprecatedPropertiesWsTest.java
it/it-tests/src/test/java/it/settings/EmailsTest.java
it/it-tests/src/test/java/it/settings/LicensesPageTest.java
it/it-tests/src/test/java/it/settings/PropertySetsTest.java
it/it-tests/src/test/java/it/settings/SettingsTest.java
it/it-tests/src/test/java/it/settings/SettingsTestRestartingOrchestrator.java
it/it-tests/src/test/java/it/ui/SourceViewerTest.java
it/it-tests/src/test/java/it/ui/UiTest.java
it/it-tests/src/test/java/it/uiExtension/OrganizationUiExtensionsTest.java
it/it-tests/src/test/java/it/uiExtension/UiExtensionsTest.java
it/it-tests/src/test/java/it/user/BaseIdentityProviderTest.java
it/it-tests/src/test/java/it/user/ForceAuthenticationTest.java
it/it-tests/src/test/java/it/user/LocalAuthenticationTest.java
it/it-tests/src/test/java/it/user/MyAccountPageTest.java
it/it-tests/src/test/java/it/user/OAuth2IdentityProviderTest.java
it/it-tests/src/test/java/it/user/OnboardingTest.java
it/it-tests/src/test/java/it/user/OrganizationIdentityProviderTest.java
it/it-tests/src/test/java/it/webhook/WebhooksTest.java
it/it-tests/src/test/java/org/sonarqube/test/GroupTester.java [new file with mode: 0644]
it/it-tests/src/test/java/org/sonarqube/test/OrganizationTester.java [new file with mode: 0644]
it/it-tests/src/test/java/org/sonarqube/test/QProfileTester.java [new file with mode: 0644]
it/it-tests/src/test/java/org/sonarqube/test/Session.java [new file with mode: 0644]
it/it-tests/src/test/java/org/sonarqube/test/Tester.java [new file with mode: 0644]
it/it-tests/src/test/java/org/sonarqube/test/UserTester.java [new file with mode: 0644]
it/it-tests/src/test/java/pageobjects/EncryptionPage.java
it/it-tests/src/test/java/pageobjects/Navigation.java
it/it-tests/src/test/java/pageobjects/NotificationsPage.java
it/it-tests/src/test/java/pageobjects/RulesPage.java
it/it-tests/src/test/java/util/ItUtils.java
it/it-tests/src/test/java/util/OrganizationRule.java [deleted file]
it/it-tests/src/test/java/util/OrganizationSupport.java [deleted file]
it/it-tests/src/test/java/util/QualityProfileRule.java [deleted file]
it/it-tests/src/test/java/util/QualityProfileSupport.java [deleted file]
it/it-tests/src/test/java/util/user/UserRule.java
it/it-tests/src/test/resources/organization/OrganizationQualityProfilesUiTest/should_copy.html
it/it-tests/src/test/resources/organization/OrganizationQualityProfilesUiTest/should_create.html
it/it-tests/src/test/resources/organization/OrganizationQualityProfilesUiTest/should_delete.html
it/it-tests/src/test/resources/organization/OrganizationQualityProfilesUiTest/should_rename.html
it/it-tests/src/test/resources/organization/OrganizationQualityProfilesUiTest/should_restore.html
it/it-tests/src/test/resources/organization/OrganizationQualityProfilesUiTest/should_set_default.html
it/it-tests/src/test/resources/qualityProfile/QualityProfilesUiTest/should_copy.html
it/it-tests/src/test/resources/qualityProfile/QualityProfilesUiTest/should_create.html
it/it-tests/src/test/resources/qualityProfile/QualityProfilesUiTest/should_delete.html
it/it-tests/src/test/resources/qualityProfile/QualityProfilesUiTest/should_rename.html
it/it-tests/src/test/resources/qualityProfile/QualityProfilesUiTest/should_restore.html
it/it-tests/src/test/resources/qualityProfile/QualityProfilesUiTest/should_set_default.html
sonar-ws/src/main/java/org/sonarqube/ws/client/DefaultWsClient.java
sonar-ws/src/main/java/org/sonarqube/ws/client/WsClient.java
sonar-ws/src/main/java/org/sonarqube/ws/client/organization/OrganizationService.java
sonar-ws/src/main/java/org/sonarqube/ws/client/qualityprofile/ChangeParentRequest.java
sonar-ws/src/main/java/org/sonarqube/ws/client/qualityprofile/DeleteRequest.java [deleted file]
sonar-ws/src/main/java/org/sonarqube/ws/client/qualityprofile/QualityProfilesService.java
sonar-ws/src/main/java/org/sonarqube/ws/client/user/UsersService.java
sonar-ws/src/main/java/org/sonarqube/ws/client/user/UsersWsParameters.java
sonar-ws/src/test/java/org/sonarqube/ws/client/qualityprofile/QualityProfilesServiceTest.java

diff --git a/cix.sh b/cix.sh
index 0748eaa9287e298e8df87a5dfc558f9baa6adeaa..60953121d3825bc0aa388b0b5799b205389c0ea9 100755 (executable)
--- a/cix.sh
+++ b/cix.sh
@@ -18,12 +18,6 @@ case "$RUN_ACTIVITY" in
     ./run-integration-tests.sh "${CATEGORY}" "http://infra.internal.sonarsource.com/jenkins/orch-${DB_ENGINE}.properties"
     ;;
 
-  run-integration-tests-*)
-    CATEGORY=$(sed "s/run-integration-tests-//g" <<< $RUN_ACTIVITY)
-
-    ./run-integration-tests.sh "${CATEGORY}" "http://infra.internal.sonarsource.com/jenkins/orch-embedded.properties"
-    ;;
-
   run-it-released-plugins)
     ./run-integration-tests.sh "Plugins" "http://infra.internal.sonarsource.com/jenkins/orch-h2.properties"
     ;;
index 4c424d0c862d68560e6bef2944cdbfe079fbbe35..cbb752d4a711528e93d8019964e98ca366a91ede 100644 (file)
@@ -46,7 +46,6 @@ import it.user.ForceAuthenticationTest;
 import it.user.LocalAuthenticationTest;
 import it.user.MyAccountPageTest;
 import it.user.OAuth2IdentityProviderTest;
-import it.user.OnboardingTest;
 import it.ws.WsLocalCallTest;
 import it.ws.WsTest;
 import org.junit.ClassRule;
@@ -66,7 +65,6 @@ import static util.ItUtils.xooPlugin;
   // user
   MyAccountPageTest.class,
   FavoritesWsTest.class,
-  OnboardingTest.class,
   // authentication
   ForceAuthenticationTest.class,
   LocalAuthenticationTest.class,
index b7047fcc2de5e9cbf939cff14bd6fc398cb14748..4d952af58b954d7bb5bce8b033e9cd60ede697b8 100644 (file)
@@ -25,6 +25,7 @@ import it.serverSystem.ServerSystemRestartingOrchestrator;
 import it.settings.LicensesPageTest;
 import it.settings.SettingsTestRestartingOrchestrator;
 import it.updateCenter.UpdateCenterTest;
+import it.user.OnboardingTest;
 import it.user.RealmAuthenticationTest;
 import it.user.SsoAuthenticationTest;
 import org.junit.runner.RunWith;
@@ -45,7 +46,8 @@ import org.junit.runners.Suite;
   // update center
   UpdateCenterTest.class,
   RealmAuthenticationTest.class,
-  SsoAuthenticationTest.class
+  SsoAuthenticationTest.class,
+  OnboardingTest.class
 })
 public class Category5Suite {
 
index 6177ad28c3e96c68f48885c3b0d4b31ccdb64627..75f6e0163d403aa41c74b4ad18e56b94cb633398 100644 (file)
@@ -48,8 +48,7 @@ public class ProjectsAdministrationTest {
   @Rule
   public UserRule userRule = UserRule.from(orchestrator);
 
-  @Rule
-  public Navigation nav = Navigation.get(orchestrator);
+  private Navigation nav = Navigation.create(orchestrator);
 
   private String adminUser;
 
index 4ebab0ec95853e750dc15c307b30d56756b98cb3..0dd27ca82fd61c6e14ca7eda472bfe44788b0e7f 100644 (file)
@@ -366,7 +366,7 @@ public class IssueCreationDateTest extends AbstractIssueTest {
     private static Date getAnalysisDate(Function<List<ProjectAnalyses.Analysis>, Optional<ProjectAnalyses.Analysis>> chooseItem) {
       return Optional.of(
         ItUtils.newWsClient(ORCHESTRATOR)
-          .projectAnanlysis()
+          .projectAnalysis()
           .search(SearchRequest.builder().setProject(SAMPLE_PROJECT_KEY).build())
           .getAnalysesList())
         .flatMap(chooseItem)
index d7559501931a5988a0e03df0f57bee57d8235be5..f5563924b6dc2946f26534eb07a14bada1c27434 100644 (file)
@@ -29,20 +29,18 @@ import org.junit.Before;
 import org.junit.ClassRule;
 import org.junit.Rule;
 import org.junit.Test;
-import org.sonarqube.ws.Organizations;
+import org.sonarqube.test.Tester;
+import org.sonarqube.ws.Organizations.Organization;
+import org.sonarqube.ws.WsUsers.CreateWsResponse.User;
 import org.sonarqube.ws.client.issue.SearchWsRequest;
 import org.sonarqube.ws.client.permission.AddUserWsRequest;
 import org.sonarqube.ws.client.project.CreateRequest;
 import util.ItUtils;
-import util.OrganizationRule;
-import util.user.UserRule;
 
 import static java.util.Arrays.asList;
 import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
 import static org.assertj.core.api.Assertions.assertThat;
-import static util.ItUtils.newAdminWsClient;
 import static util.ItUtils.newProjectKey;
-import static util.ItUtils.newUserWsClient;
 import static util.ItUtils.projectDir;
 import static util.ItUtils.restoreProfile;
 
@@ -53,23 +51,22 @@ public class IssueTagsTest {
 
   @ClassRule
   public static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
+
   @Rule
-  public UserRule userRule = new UserRule(orchestrator);
-  @Rule
-  public OrganizationRule organizationRule = new OrganizationRule(orchestrator);
+  public Tester tester = new Tester(orchestrator);
 
-  private Organizations.Organization organization;
+  private Organization organization;
 
   @Before
   public void setUp() {
-    organization = organizationRule.create();
+    organization = tester.organizations().generate();
   }
 
   @Test
-  public void getTags()  {
+  public void getTags() {
     restoreProfile(orchestrator, IssueTagsTest.class.getResource("/issue/one-issue-per-line-profile.xml"), organization.getKey());
     String projectKey = newProjectKey();
-    ItUtils.newAdminWsClient(orchestrator).projects().create(
+    tester.wsClient().projects().create(
       CreateRequest.builder()
         .setKey(projectKey)
         .setOrganization(organization.getKey())
@@ -78,8 +75,8 @@ public class IssueTagsTest {
         .build());
     analyzeProject(projectKey);
 
-    String issue = newAdminWsClient(orchestrator).issues().search(new SearchWsRequest()).getIssues(0).getKey();
-    newAdminWsClient(orchestrator).issues().setTags(issue, "bla", "blubb");
+    String issue = tester.wsClient().issues().search(new SearchWsRequest()).getIssues(0).getKey();
+    tester.wsClient().issues().setTags(issue, "bla", "blubb");
 
     String[] publicTags = {"bad-practice", "convention", "pitfall"};
     String[] privateTags = {"bad-practice", "bla", "blubb", "convention", "pitfall"};
@@ -88,48 +85,44 @@ public class IssueTagsTest {
     // anonymous must not see custom tags of private project
     {
       String anonymous = null;
-      String anonymousPassword = null;
-      assertTags(anonymous, anonymousPassword, organization.getKey(), publicTags);
-      assertTags(anonymous, anonymousPassword, defaultOrganization, publicTags);
+      assertTags(anonymous, organization.getKey(), publicTags);
+      assertTags(anonymous, defaultOrganization, publicTags);
     }
 
     // stranger must not see custom tags of private project
     {
-      String stranger = randomAlphabetic(10).toLowerCase();
-      String strangerPassword = randomAlphabetic(8);
-      userRule.createUser(stranger, strangerPassword);
-      assertTags(stranger, strangerPassword, organization.getKey(), publicTags);
-      assertTags(stranger, strangerPassword, defaultOrganization, publicTags);
+      User stranger = tester.users().generate();
+      assertTags(stranger.getLogin(), organization.getKey(), publicTags);
+      assertTags(stranger.getLogin(), defaultOrganization, publicTags);
     }
 
     // member with user permission must be able to see custom tags of private project, if he provides the organization parameter
     {
-      String member = randomAlphabetic(10).toLowerCase();
-      String memberPassword = randomAlphabetic(8);
-      userRule.createUser(member, memberPassword);
-      addMember(member);
+      User member = tester.users().generate();
+      addMemberToOrganization(member);
       grantUserPermission(projectKey, member);
-      assertTags(member, memberPassword, organization.getKey(), privateTags);
-      assertTags(member, memberPassword, defaultOrganization, publicTags);
+      assertTags(member.getLogin(), organization.getKey(), privateTags);
+      assertTags(member.getLogin(), defaultOrganization, publicTags);
     }
   }
 
-  private void addMember(String member) {
-    newAdminWsClient(orchestrator).organizations().addMember(organization.getKey(), member);
+  private void addMemberToOrganization(User member) {
+    tester.organizations().service().addMember(organization.getKey(), member.getLogin());
   }
 
-  private void grantUserPermission(String projectKey, String member) {
-    newAdminWsClient(orchestrator).permissions().addUser(
+  private void grantUserPermission(String projectKey, User member) {
+    tester.wsClient().permissions().addUser(
       new AddUserWsRequest()
-        .setLogin(member)
+        .setLogin(member.getLogin())
         .setPermission("user")
         .setProjectKey(projectKey));
   }
 
-  private void assertTags(@Nullable String user, @Nullable String password, @Nullable String organization, String... expectedTags) {
+  private void assertTags(@Nullable String userLogin, @Nullable String organization, String... expectedTags) {
     assertThat(
       (List<String>) ItUtils.jsonToMap(
-        newUserWsClient(orchestrator, user, password)
+        tester.as(userLogin)
+          .wsClient()
           .issues()
           .getTags(organization)
           .content())
index feff031efb1237552108a8079d59d4fd04c7dfd7..3af55ed447f0aee838a7261e53070411a038f43a 100644 (file)
@@ -43,8 +43,7 @@ public class IssuesPageTest {
   @Rule
   public UserRule userRule = UserRule.from(ORCHESTRATOR);
 
-  @Rule
-  public Navigation nav = Navigation.get(ORCHESTRATOR);
+  public Navigation nav = Navigation.create(ORCHESTRATOR);
 
   private String adminUser;
 
@@ -73,6 +72,7 @@ public class IssuesPageTest {
 
   @Test
   public void should_not_display_actions() {
+    Navigation nav = Navigation.create(ORCHESTRATOR);
     IssuesPage page = nav.openIssues();
     Issue issue = page.getFirstIssue();
     issue.shouldNotAllowAssign().shouldNotAllowChangeType();
index ae0861dbbcee099a841076907c595298ee00a849..ffe6ac715f34f8bf4d7402798e4c135e791ccd22 100644 (file)
@@ -28,176 +28,154 @@ import org.junit.Before;
 import org.junit.ClassRule;
 import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.sonarqube.test.Tester;
 import org.sonarqube.ws.Issues;
 import org.sonarqube.ws.Issues.Issue;
-import org.sonarqube.ws.client.HttpException;
-import org.sonarqube.ws.client.WsClient;
+import org.sonarqube.ws.Organizations;
+import org.sonarqube.ws.WsUsers.CreateWsResponse.User;
 import org.sonarqube.ws.client.issue.AssignRequest;
 import org.sonarqube.ws.client.issue.BulkChangeRequest;
 import org.sonarqube.ws.client.issue.SearchWsRequest;
 import org.sonarqube.ws.client.project.CreateRequest;
 import org.sonarqube.ws.client.qualityprofile.AddProjectRequest;
-import pageobjects.Navigation;
 import pageobjects.issues.IssuesPage;
-import util.OrganizationRule;
 import util.issue.IssueRule;
-import util.user.UserRule;
 
 import static java.lang.String.format;
 import static java.util.Collections.singletonList;
 import static org.assertj.core.api.Assertions.assertThat;
-import static util.ItUtils.newAdminWsClient;
-import static util.ItUtils.newOrganizationKey;
+import static util.ItUtils.expectHttpError;
 import static util.ItUtils.restoreProfile;
 import static util.ItUtils.runProjectAnalysis;
 import static util.ItUtils.setServerProperty;
 
 public class OrganizationIssueAssignTest {
 
-  private final static String ORGANIZATION_KEY = newOrganizationKey();
-  private final static String OTHER_ORGANIZATION_KEY = newOrganizationKey();
   private final static String SAMPLE_PROJECT_KEY = "sample";
-  private static final String ASSIGNEE_LOGIN = "bob";
-  private static final String OTHER_LOGIN = "neo";
-
-  @Rule
-  public ExpectedException expectedException = ExpectedException.none();
 
   @ClassRule
   public static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
   @Rule
-  public OrganizationRule organizations = new OrganizationRule(orchestrator);
-  @Rule
-  public UserRule userRule = UserRule.from(orchestrator);
-  @ClassRule
-  public static IssueRule issueRule = IssueRule.from(orchestrator);
+  public Tester tester = new Tester(orchestrator);
+
   @Rule
-  public Navigation nav = Navigation.get(orchestrator);
+  public IssueRule issueRule = IssueRule.from(orchestrator);
 
-  private WsClient adminClient = newAdminWsClient(orchestrator);
-  private String adminUser;
+  private Organizations.Organization org1;
+  private Organizations.Organization org2;
+  private User user;
 
   @Before
   public void setUp() throws Exception {
-    createOrganization(ORGANIZATION_KEY);
-    restoreProfile(orchestrator, getClass().getResource("/organization/IssueAssignTest/one-issue-per-file-profile.xml"), ORGANIZATION_KEY);
-    adminUser = userRule.createRootUser();
+    org1 = tester.organizations().generate();
+    org2 = tester.organizations().generate();
+    user = tester.users().generate();
+    restoreProfile(orchestrator, getClass().getResource("/organization/IssueAssignTest/one-issue-per-file-profile.xml"), org1.getKey());
   }
 
   @Test
-  public void auto_assign_issues_to_user_if_default_assignee_is_member_of_project_organization() throws Exception {
-    userRule.createUser(ASSIGNEE_LOGIN, ASSIGNEE_LOGIN);
-    adminClient.organizations().addMember(ORGANIZATION_KEY, ASSIGNEE_LOGIN);
-    provisionProject(SAMPLE_PROJECT_KEY, ORGANIZATION_KEY);
-    setServerProperty(orchestrator, "sample", "sonar.issues.defaultAssigneeLogin", ASSIGNEE_LOGIN);
+  public void auto_assign_issues_to_user_if_default_assignee_is_member_of_project_organization() {
+    tester.organizations().addMember(org1, user);
+
+    provisionProject(SAMPLE_PROJECT_KEY, org1.getKey());
+    setServerProperty(orchestrator, "sample", "sonar.issues.defaultAssigneeLogin", user.getLogin());
 
-    analyseProject(SAMPLE_PROJECT_KEY, ORGANIZATION_KEY);
+    analyseProject(SAMPLE_PROJECT_KEY, org1.getKey());
 
-    assertThat(issueRule.getRandomIssue().getAssignee()).isEqualTo(ASSIGNEE_LOGIN);
+    assertThat(issueRule.getRandomIssue().getAssignee()).isEqualTo(user.getLogin());
   }
 
   @Test
-  public void does_not_auto_assign_issues_to_user_if_default_assignee_is_not_member_of_project_organization() throws Exception {
-    createOrganization(OTHER_ORGANIZATION_KEY);
-    userRule.createUser(ASSIGNEE_LOGIN, ASSIGNEE_LOGIN);
-    adminClient.organizations().addMember(OTHER_ORGANIZATION_KEY, ASSIGNEE_LOGIN);
-    provisionProject(SAMPLE_PROJECT_KEY, ORGANIZATION_KEY);
-    setServerProperty(orchestrator, "sample", "sonar.issues.defaultAssigneeLogin", ASSIGNEE_LOGIN);
+  public void does_not_auto_assign_issues_to_user_if_default_assignee_is_not_member_of_project_organization() {
+    tester.organizations().addMember(org2, user);
+    provisionProject(SAMPLE_PROJECT_KEY, org1.getKey());
+    setServerProperty(orchestrator, "sample", "sonar.issues.defaultAssigneeLogin", user.getLogin());
 
-    analyseProject(SAMPLE_PROJECT_KEY, ORGANIZATION_KEY);
+    analyseProject(SAMPLE_PROJECT_KEY, org1.getKey());
 
     assertThat(issueRule.getRandomIssue().hasAssignee()).isFalse();
   }
 
   @Test
-  public void assign_issue_to_user_being_member_of_same_organization_as_project_issue_organization() throws Exception {
-    userRule.createUser(ASSIGNEE_LOGIN, ASSIGNEE_LOGIN);
-    adminClient.organizations().addMember(ORGANIZATION_KEY, ASSIGNEE_LOGIN);
-    provisionAndAnalyseProject(SAMPLE_PROJECT_KEY, ORGANIZATION_KEY);
+  public void assign_issue_to_user_being_member_of_same_organization_as_project_issue_organization() {
+    tester.organizations().addMember(org1, user);
+    provisionAndAnalyseProject(SAMPLE_PROJECT_KEY, org1.getKey());
     Issue issue = issueRule.getRandomIssue();
 
-    adminClient.issues().assign(new AssignRequest(issue.getKey(), ASSIGNEE_LOGIN));
+    assignIssueTo(issue, user);
 
-    assertThat(issueRule.getByKey(issue.getKey()).getAssignee()).isEqualTo(ASSIGNEE_LOGIN);
+    assertThat(issueRule.getByKey(issue.getKey()).getAssignee()).isEqualTo(user.getLogin());
   }
 
   @Test
-  public void fail_to_assign_issue_to_user_not_being_member_of_same_organization_as_project_issue_organization() throws Exception {
-    createOrganization(OTHER_ORGANIZATION_KEY);
-    userRule.createUser(ASSIGNEE_LOGIN, ASSIGNEE_LOGIN);
-    adminClient.organizations().addMember(OTHER_ORGANIZATION_KEY, ASSIGNEE_LOGIN);
-    provisionAndAnalyseProject(SAMPLE_PROJECT_KEY, ORGANIZATION_KEY);
+  public void fail_to_assign_issue_to_user_not_being_member_of_same_organization_as_project_issue_organization() {
+    tester.organizations().addMember(org2, user);
+    provisionAndAnalyseProject(SAMPLE_PROJECT_KEY, org1.getKey());
     Issue issue = issueRule.getRandomIssue();
 
-    expectedException.expect(HttpException.class);
-    expectedException.expectMessage(format("User 'bob' is not member of organization '%s'", ORGANIZATION_KEY));
-
-    adminClient.issues().assign(new AssignRequest(issue.getKey(), ASSIGNEE_LOGIN));
+    expectHttpError(400,
+      format("User '%s' is not member of organization '%s'", user.getLogin(), org1.getKey()),
+      () -> assignIssueTo(issue, user));
   }
 
   @Test
-  public void bulk_assign_issues_to_user_being_only_member_of_same_organization_as_project_issue_organization() throws Exception {
-    createOrganization(OTHER_ORGANIZATION_KEY);
-    restoreProfile(orchestrator, getClass().getResource("/organization/IssueAssignTest/one-issue-per-file-profile.xml"), OTHER_ORGANIZATION_KEY);
-    userRule.createUser(ASSIGNEE_LOGIN, ASSIGNEE_LOGIN);
-    // User is only member of "organization-key", not of "other-organization-key"
-    adminClient.organizations().addMember(ORGANIZATION_KEY, ASSIGNEE_LOGIN);
-    provisionAndAnalyseProject(SAMPLE_PROJECT_KEY, ORGANIZATION_KEY);
-    provisionAndAnalyseProject("sample2", OTHER_ORGANIZATION_KEY);
+  public void bulk_assign_issues_to_user_being_only_member_of_same_organization_as_project_issue_organization() {
+    restoreProfile(orchestrator, getClass().getResource("/organization/IssueAssignTest/one-issue-per-file-profile.xml"), org2.getKey());
+    // User is only member of org1, not of org2
+    tester.organizations().addMember(org1, user);
+    provisionAndAnalyseProject(SAMPLE_PROJECT_KEY, org1.getKey());
+    provisionAndAnalyseProject("sample2", org2.getKey());
     List<String> issues = issueRule.search(new org.sonarqube.ws.client.issue.SearchWsRequest()).getIssuesList().stream().map(Issue::getKey).collect(Collectors.toList());
 
-    Issues.BulkChangeWsResponse response = adminClient.issues().bulkChange(BulkChangeRequest.builder().setIssues(issues).setAssign(ASSIGNEE_LOGIN).build());
+    Issues.BulkChangeWsResponse response = tester.wsClient().issues()
+      .bulkChange(BulkChangeRequest.builder().setIssues(issues).setAssign(user.getLogin()).build());
 
     assertThat(response.getIgnored()).isGreaterThan(0);
-    assertThat(issueRule.search(new SearchWsRequest().setProjectKeys(singletonList("sample"))).getIssuesList()).extracting(Issue::getAssignee).containsOnly(ASSIGNEE_LOGIN);
-    assertThat(issueRule.search(new SearchWsRequest().setProjectKeys(singletonList("sample2"))).getIssuesList()).extracting(Issue::hasAssignee).containsOnly(false);
+    assertThat(issueRule.search(new SearchWsRequest().setProjectKeys(singletonList("sample"))).getIssuesList()).extracting(Issue::getAssignee)
+      .containsOnly(user.getLogin());
+    assertThat(issueRule.search(new SearchWsRequest().setProjectKeys(singletonList("sample2"))).getIssuesList()).extracting(Issue::hasAssignee)
+      .containsOnly(false);
   }
 
   @Test
   public void single_assign_search_show_only_members_in_global_issues() {
-    createOrganization(OTHER_ORGANIZATION_KEY);
-    userRule.createUser(ASSIGNEE_LOGIN, ASSIGNEE_LOGIN);
-    adminClient.organizations().addMember(ORGANIZATION_KEY, ASSIGNEE_LOGIN);
-    userRule.createUser(OTHER_LOGIN, "pwd");
-    provisionAndAnalyseProject(SAMPLE_PROJECT_KEY, ORGANIZATION_KEY);
-    IssuesPage page = nav.logIn().submitCredentials(adminUser).openIssues();
+    tester.organizations().addMember(org1, user);
+    User otherUser = tester.users().generate();
+    provisionAndAnalyseProject(SAMPLE_PROJECT_KEY, org1.getKey());
+    IssuesPage page = tester.openBrowser().logIn().submitCredentials(user.getLogin()).openIssues();
     page.getFirstIssue()
       .shouldAllowAssign()
-      .assigneeSearchResultCount(OTHER_LOGIN, 0)
-      .assigneeSearchResultCount(ASSIGNEE_LOGIN, 1);
+      .assigneeSearchResultCount(otherUser.getLogin(), 0)
+      .assigneeSearchResultCount(user.getLogin(), 1);
   }
 
   @Test
   public void bulk_assign_search_only_members_of_organization_in_project_issues() {
-    createOrganization(OTHER_ORGANIZATION_KEY);
-    userRule.createUser(ASSIGNEE_LOGIN, ASSIGNEE_LOGIN);
-    adminClient.organizations().addMember(ORGANIZATION_KEY, ASSIGNEE_LOGIN);
-    userRule.createUser(OTHER_LOGIN, "pwd");
-    provisionAndAnalyseProject(SAMPLE_PROJECT_KEY, ORGANIZATION_KEY);
-    IssuesPage page = nav.logIn().submitCredentials(adminUser).openComponentIssues(SAMPLE_PROJECT_KEY);
+    tester.organizations().addMember(org1, user);
+    User otherUser = tester.users().generate();
+
+    provisionAndAnalyseProject(SAMPLE_PROJECT_KEY, org1.getKey());
+    IssuesPage page = tester.openBrowser()
+      .logIn().submitCredentials(user.getLogin())
+      .openComponentIssues(SAMPLE_PROJECT_KEY);
     page
       .bulkChangeOpen()
-      .bulkChangeAssigneeSearchCount(ASSIGNEE_LOGIN, 1)
-      .bulkChangeAssigneeSearchCount(OTHER_LOGIN, 0);
+      .bulkChangeAssigneeSearchCount(user.getLogin(), 1)
+      .bulkChangeAssigneeSearchCount(otherUser.getLogin(), 0);
   }
 
   @Test
   public void bulk_assign_search_all_users_in_global_issues() {
-    createOrganization(OTHER_ORGANIZATION_KEY);
-    userRule.createUser(ASSIGNEE_LOGIN, ASSIGNEE_LOGIN);
-    adminClient.organizations().addMember(ORGANIZATION_KEY, ASSIGNEE_LOGIN);
-    userRule.createUser(OTHER_LOGIN, "pwd");
-    provisionAndAnalyseProject(SAMPLE_PROJECT_KEY, ORGANIZATION_KEY);
-    IssuesPage page = nav.logIn().submitCredentials(adminUser).openIssues();
+    tester.organizations().addMember(org1, user);
+    User otherUser = tester.users().generate();
+    provisionAndAnalyseProject(SAMPLE_PROJECT_KEY, org1.getKey());
+    IssuesPage page = tester.openBrowser()
+      .logIn().submitCredentials(user.getLogin())
+      .openIssues();
     page
       .bulkChangeOpen()
-      .bulkChangeAssigneeSearchCount(ASSIGNEE_LOGIN, 1)
-      .bulkChangeAssigneeSearchCount(OTHER_LOGIN, 1);
-  }
-
-  private void createOrganization(String organizationKey) {
-    organizations.create(o -> o.setKey(organizationKey).setName(organizationKey));
+      .bulkChangeAssigneeSearchCount(user.getLogin(), 1)
+      .bulkChangeAssigneeSearchCount(otherUser.getLogin(), 1);
   }
 
   private void provisionAndAnalyseProject(String projectKey, String organization) {
@@ -206,7 +184,7 @@ public class OrganizationIssueAssignTest {
   }
 
   private void provisionProject(String projectKey, String organization) {
-    adminClient.projects().create(
+    tester.wsClient().projects().create(
       CreateRequest.builder()
         .setKey(projectKey)
         .setName(projectKey)
@@ -226,7 +204,7 @@ public class OrganizationIssueAssignTest {
   }
 
   private void addQualityProfileToProject(String organization, String projectKey) {
-    adminClient.qualityProfiles().addProject(
+    tester.wsClient().qualityProfiles().addProject(
       AddProjectRequest.builder()
         .setProjectKey(projectKey)
         .setOrganization(organization)
@@ -234,4 +212,8 @@ public class OrganizationIssueAssignTest {
         .setProfileName("one-issue-per-file-profile")
         .build());
   }
+
+  private Issues.Operation assignIssueTo(Issue issue, User u) {
+    return tester.wsClient().issues().assign(new AssignRequest(issue.getKey(), u.getLogin()));
+  }
 }
index b888cf9e11464304812c2d34d545111b34b80c3f..1537c8af6c34663348d3357001b13836f016de69 100644 (file)
@@ -22,16 +22,18 @@ package it.lite;
 import com.sonar.orchestrator.Orchestrator;
 import org.junit.BeforeClass;
 import org.junit.ClassRule;
+import org.junit.Rule;
 import org.junit.Test;
+import org.sonarqube.test.Tester;
 import org.sonarqube.ws.Issues;
 import org.sonarqube.ws.WsComponents;
 import org.sonarqube.ws.WsMeasures;
-import org.sonarqube.ws.client.WsClient;
 import org.sonarqube.ws.client.component.TreeWsRequest;
+import org.sonarqube.ws.client.issue.IssuesService;
 import org.sonarqube.ws.client.issue.SearchWsRequest;
 import org.sonarqube.ws.client.measure.ComponentTreeWsRequest;
 import org.sonarqube.ws.client.measure.ComponentWsRequest;
-import util.ItUtils;
+import org.sonarqube.ws.client.measure.MeasuresService;
 
 import static java.util.Arrays.asList;
 import static java.util.Collections.singletonList;
@@ -44,34 +46,36 @@ public class LiteTest {
   private static final String PROJECT_KEY = "com.sonarsource.it.samples:multi-modules-sample";
 
   @ClassRule
-  public static final Orchestrator ORCHESTRATOR = Orchestrator.builderEnv()
+  public static Orchestrator orchestrator = Orchestrator.builderEnv()
     .setOrchestratorProperty("sonar.web.context", "/sonarqube")
     .addPlugin(xooPlugin())
     .build();
 
-  private static WsClient wsClient;
+  @Rule
+  public Tester tester = new Tester(orchestrator)
+    .disableOrganizations();
 
   @BeforeClass
   public static void setUp() {
-    runProjectAnalysis(ORCHESTRATOR, "shared/xoo-multi-modules-sample");
-    wsClient = ItUtils.newWsClient(ORCHESTRATOR);
+    runProjectAnalysis(orchestrator, "shared/xoo-multi-modules-sample");
   }
 
   @Test
   public void call_issues_ws() {
     // all issues
-    Issues.SearchWsResponse response = wsClient.issues().search(new SearchWsRequest());
+    IssuesService issuesService = tester.wsClient().issues();
+    Issues.SearchWsResponse response = issuesService.search(new SearchWsRequest());
     assertThat(response.getIssuesCount()).isGreaterThan(0);
 
     // project issues
-    response = wsClient.issues().search(new SearchWsRequest().setProjectKeys(singletonList(PROJECT_KEY)));
+    response = issuesService.search(new SearchWsRequest().setProjectKeys(singletonList(PROJECT_KEY)));
     assertThat(response.getIssuesCount()).isGreaterThan(0);
   }
 
   @Test
   public void call_components_ws() {
     // files in project
-    WsComponents.TreeWsResponse tree = wsClient.components().tree(new TreeWsRequest()
+    WsComponents.TreeWsResponse tree = tester.wsClient().components().tree(new TreeWsRequest()
       .setBaseComponentKey(PROJECT_KEY)
       .setQualifiers(singletonList("FIL")));
     assertThat(tree.getComponentsCount()).isEqualTo(4);
@@ -84,13 +88,14 @@ public class LiteTest {
   @Test
   public void call_measures_ws() {
     // project measures
-    WsMeasures.ComponentWsResponse component = wsClient.measures().component(new ComponentWsRequest()
+    MeasuresService measuresService = tester.wsClient().measures();
+    WsMeasures.ComponentWsResponse component = measuresService.component(new ComponentWsRequest()
       .setComponentKey(PROJECT_KEY)
       .setMetricKeys(asList("lines", "ncloc", "files")));
     assertThat(component.getComponent().getMeasuresCount()).isEqualTo(3);
 
     // file measures
-    WsMeasures.ComponentTreeWsResponse tree = wsClient.measures().componentTree(new ComponentTreeWsRequest()
+    WsMeasures.ComponentTreeWsResponse tree = measuresService.componentTree(new ComponentTreeWsRequest()
       .setBaseComponentKey(PROJECT_KEY)
       .setQualifiers(singletonList("FIL"))
       .setMetricKeys(asList("lines", "ncloc")));
index cc3b24792ba99b244d8b4f717ea49c6970e7086f..b0054d9d3af091d1008c2dba798d60cf79833d8d 100644 (file)
@@ -48,8 +48,7 @@ public class ProjectDashboardTest {
   @Rule
   public UserRule userRule = UserRule.from(orchestrator);
 
-  @Rule
-  public Navigation nav = Navigation.get(orchestrator);
+  private Navigation nav = Navigation.create(orchestrator);
 
   private static WsClient wsClient;
   private String adminUser;
@@ -72,7 +71,7 @@ public class ProjectDashboardTest {
   public void display_size() {
     executeBuild("shared/xoo-sample", "sample", "Sample");
 
-    ProjectDashboardPage page = nav.openProjectDashboard("sample");
+    ProjectDashboardPage page = Navigation.create(orchestrator).openProjectDashboard("sample");
 
     page.getLinesOfCode().should(hasText("13"));
     page.getLanguageDistribution().should(hasText("Xoo"), hasText("13"));
@@ -88,7 +87,7 @@ public class ProjectDashboardTest {
         .setParam("project", "sample")
         .setParam("tags", "foo,bar,baz"));
 
-    ProjectDashboardPage page = nav.openProjectDashboard("sample");
+    ProjectDashboardPage page = Navigation.create(orchestrator).openProjectDashboard("sample");
     page
       .shouldHaveTags("foo", "bar", "baz")
       .shouldNotBeEditable();
@@ -125,6 +124,7 @@ public class ProjectDashboardTest {
   @Test
   @Ignore("there is no more place to show the error")
   public void display_a_nice_error_when_requesting_unknown_project() {
+    Navigation nav = Navigation.create(orchestrator);
     nav.open("/dashboard/index?id=unknown");
     nav.getErrorMessage().should(text("The requested project does not exist. Either it has never been analyzed successfully or it has been deleted."));
     // TODO verify that on global homepage
index b69af1e0aad43113dbea91a03077ad5e937d9e45..8c83f7bc3a88f1cc1bfd43980ffc92872cde6b2c 100644 (file)
@@ -44,16 +44,14 @@ public class ProjectMeasuresPageTest {
       SonarScanner
         .create(projectDir("shared/xoo-sample"))
         .setProperty("sonar.projectKey", "project-measures-page-test-project")
-        .setProperty("sonar.projectName", "ProjectMeasuresPageTest Project")
-    );
+        .setProperty("sonar.projectName", "ProjectMeasuresPageTest Project"));
 
     // one more time
     orchestrator.executeBuild(
       SonarScanner
         .create(projectDir("shared/xoo-sample"))
         .setProperty("sonar.projectKey", "project-measures-page-test-project")
-        .setProperty("sonar.projectName", "ProjectMeasuresPageTest Project")
-    );
+        .setProperty("sonar.projectName", "ProjectMeasuresPageTest Project"));
   }
 
   @Test
@@ -73,7 +71,7 @@ public class ProjectMeasuresPageTest {
 
   @Test
   public void should_show_history() {
-    Navigation nav = Navigation.get(orchestrator);
+    Navigation nav = Navigation.create(orchestrator);
     nav.open("/component_measures/metric/reliability_rating/history?id=project-measures-page-test-project");
     $(".line-chart").shouldBe(visible);
     $$(".line-chart-tick-x").shouldHaveSize(5);
index 47bfede4f9a0c073ee68a0d89b5efbd810ec42a9..03f40dc23d8410f2ca042278a87878eaa30c739b 100644 (file)
@@ -101,7 +101,7 @@ public class DifferentialPeriodsTest {
     assertThat(getLeakPeriodValue(orchestrator, PROJECT_KEY, "violations")).isEqualTo(17);
 
     // Check on ui that it's possible to define leak period on project
-    Navigation.get(orchestrator).openHomepage().logIn().submitCredentials(adminUser).openSettings("sample")
+    Navigation.create(orchestrator).openHome().logIn().submitCredentials(adminUser).openSettings("sample")
       .assertSettingDisplayed("sonar.leak.period");
   }
 
index d43510e5e80261b6ae8c86518052247b267c2ccc..975db8b260e7df2ac2ae4988ef156d02d79a0224 100644 (file)
@@ -25,30 +25,24 @@ import com.sonar.orchestrator.build.SonarScanner;
 import it.Category6Suite;
 import org.junit.After;
 import org.junit.Before;
-import org.junit.BeforeClass;
 import org.junit.ClassRule;
 import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.sonarqube.test.Tester;
+import org.sonarqube.ws.Organizations;
+import org.sonarqube.ws.WsUsers.CreateWsResponse.User;
 import org.sonarqube.ws.client.GetRequest;
-import org.sonarqube.ws.client.HttpException;
-import org.sonarqube.ws.client.WsClient;
 import org.sonarqube.ws.client.WsResponse;
-import org.sonarqube.ws.client.organization.CreateWsRequest;
 import org.sonarqube.ws.client.organization.UpdateProjectVisibilityWsRequest;
 import org.sonarqube.ws.client.project.CreateRequest;
 import org.sonarqube.ws.client.project.UpdateVisibilityRequest;
 import pageobjects.Navigation;
 import util.ItUtils;
-import util.OrganizationRule;
-import util.user.UserRule;
 
 import static java.lang.String.format;
 import static org.assertj.core.api.Java6Assertions.assertThat;
-import static org.junit.Assert.fail;
 import static org.sonarqube.ws.WsCe.TaskResponse;
-import static util.ItUtils.newAdminWsClient;
-import static util.ItUtils.newOrganizationKey;
+import static util.ItUtils.expectHttpError;
 import static util.ItUtils.newProjectKey;
 import static util.ItUtils.newUserWsClient;
 import static util.ItUtils.projectDir;
@@ -57,28 +51,16 @@ import static util.ItUtils.setServerProperty;
 
 public class BillingTest {
 
-  private static final String USER_LOGIN = "USER_LOGIN";
   private static final String PROPERTY_PREVENT_ANALYSIS = "sonar.billing.preventProjectAnalysis";
 
   @ClassRule
   public static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
 
   @Rule
-  public UserRule userRule = UserRule.from(orchestrator);
-  @Rule
-  public OrganizationRule organizationRule = new OrganizationRule(orchestrator);
-  @Rule
-  public ExpectedException expectedException = ExpectedException.none();
-  @Rule
-  public Navigation nav = Navigation.get(orchestrator);
+  public Tester tester = new Tester(orchestrator);
 
-  private static WsClient adminClient;
-  private String adminUser;
-
-  @BeforeClass
-  public static void prepare() {
-    adminClient = newAdminWsClient(orchestrator);
-  }
+  private Organizations.Organization organization;
+  private User orgAdministrator;
 
   @Before
   @After
@@ -87,189 +69,178 @@ public class BillingTest {
   }
 
   @Before
-  public void createAdminUser() throws Exception {
-    adminUser = userRule.createRootUser();
+  public void setUp() {
+    organization = tester.organizations().generate();
+    orgAdministrator = tester.users().generateAdministrator(organization);
   }
 
   @Test
   public void execute_successfully_ce_analysis_on_organization() {
-    String organizationKey = createOrganization();
     setServerProperty(orchestrator, PROPERTY_PREVENT_ANALYSIS, "false");
 
-    String taskUuid = executeAnalysis(organizationKey);
+    String taskUuid = executeAnalysis(newProjectKey());
 
-    TaskResponse taskResponse = adminClient.ce().task(taskUuid);
+    TaskResponse taskResponse = tester.wsClient().ce().task(taskUuid);
     assertThat(taskResponse.getTask().hasErrorMessage()).isFalse();
   }
 
   @Test
   public void fail_to_execute_ce_analysis_on_organization() {
-    String organizationKey = createOrganization();
     setServerProperty(orchestrator, PROPERTY_PREVENT_ANALYSIS, "true");
 
-    String taskUuid = executeAnalysis(organizationKey);
+    String taskUuid = executeAnalysis(newProjectKey());
 
-    TaskResponse taskResponse = adminClient.ce().task(taskUuid);
+    TaskResponse taskResponse = tester.wsClient().ce().task(taskUuid);
     assertThat(taskResponse.getTask().hasErrorMessage()).isTrue();
-    assertThat(taskResponse.getTask().getErrorMessage()).contains(format("Organization %s cannot perform analysis", organizationKey));
+    assertThat(taskResponse.getTask().getErrorMessage()).contains(format("Organization %s cannot perform analysis", organization.getKey()));
   }
 
   @Test
   public void api_navigation_organization_returns_canUpdateProjectsVisibilityToPrivate() {
-    String organizationKey = createOrganization();
-    userRule.createUser(USER_LOGIN, USER_LOGIN);
-    adminClient.organizations().addMember(organizationKey, USER_LOGIN);
+    User user = tester.users().generate();
+    tester.organizations().addMember(organization, user);
 
     setServerProperty(orchestrator, "sonar.billing.preventUpdatingProjectsVisibilityToPrivate", "false");
-    assertWsResponseAsAdmin(new GetRequest("api/navigation/organization").setParam("organization", organizationKey), "\"canUpdateProjectsVisibilityToPrivate\":true");
+    assertWsResponseAsAdmin(new GetRequest("api/navigation/organization").setParam("organization", organization.getKey()),
+      "\"canUpdateProjectsVisibilityToPrivate\":true");
 
     setServerProperty(orchestrator, "sonar.billing.preventUpdatingProjectsVisibilityToPrivate", "true");
-    assertWsResponseAsAdmin(new GetRequest("api/navigation/organization").setParam("organization", organizationKey), "\"canUpdateProjectsVisibilityToPrivate\":false");
+    assertWsResponseAsAdmin(new GetRequest("api/navigation/organization").setParam("organization", organization.getKey()),
+      "\"canUpdateProjectsVisibilityToPrivate\":false");
 
     setServerProperty(orchestrator, "sonar.billing.preventUpdatingProjectsVisibilityToPrivate", "true");
-    assertWsResponseAsUser(new GetRequest("api/navigation/organization").setParam("organization", organizationKey), "\"canUpdateProjectsVisibilityToPrivate\":false");
+    assertWsResponseAsUser(new GetRequest("api/navigation/organization").setParam("organization", organization.getKey()),
+      "\"canUpdateProjectsVisibilityToPrivate\":false", user);
   }
 
   @Test
   public void api_navigation_component_returns_canUpdateProjectVisibilityToPrivate() {
-    String organizationKey = createOrganization();
-    String projectKey = createPublicProject(organizationKey);
+    String projectKey = createPublicProject();
 
     setServerProperty(orchestrator, "sonar.billing.preventUpdatingProjectsVisibilityToPrivate", "false");
-    assertWsResponseAsAdmin(new GetRequest("api/navigation/component").setParam("componentKey", projectKey), "\"canUpdateProjectVisibilityToPrivate\":true");
+    assertWsResponseAsAdmin(new GetRequest("api/navigation/component").setParam("componentKey", projectKey),
+      "\"canUpdateProjectVisibilityToPrivate\":true");
 
     setServerProperty(orchestrator, "sonar.billing.preventUpdatingProjectsVisibilityToPrivate", "true");
-    assertWsResponseAsAdmin(new GetRequest("api/navigation/component").setParam("componentKey", projectKey), "\"canUpdateProjectVisibilityToPrivate\":false");
+    assertWsResponseAsAdmin(new GetRequest("api/navigation/component").setParam("componentKey", projectKey),
+      "\"canUpdateProjectVisibilityToPrivate\":false");
   }
 
   @Test
   public void does_not_fail_to_update_default_projects_visibility_to_private() {
-    String organizationKey = createOrganization();
     setServerProperty(orchestrator, "sonar.billing.preventUpdatingProjectsVisibilityToPrivate", "false");
 
-    adminClient.organizations().updateProjectVisibility(UpdateProjectVisibilityWsRequest.builder().setOrganization(organizationKey).setProjectVisibility("private").build());
+    tester.wsClient().organizations().updateProjectVisibility(UpdateProjectVisibilityWsRequest.builder()
+      .setOrganization(organization.getKey())
+      .setProjectVisibility("private")
+      .build());
 
-    assertWsResponseAsAdmin(new GetRequest("api/navigation/organization").setParam("organization", organizationKey), "\"projectVisibility\":\"private\"");
+    assertWsResponseAsAdmin(new GetRequest("api/navigation/organization").setParam("organization", organization.getKey()),
+      "\"projectVisibility\":\"private\"");
   }
 
   @Test
   public void fail_to_update_organization_default_visibility_to_private() {
-    String organizationKey = createOrganization();
     setServerProperty(orchestrator, "sonar.billing.preventUpdatingProjectsVisibilityToPrivate", "true");
 
-    try {
-      adminClient.organizations().updateProjectVisibility(UpdateProjectVisibilityWsRequest.builder().setOrganization(organizationKey).setProjectVisibility("private").build());
-      fail();
-    } catch (HttpException ex) {
-      assertThat(ex.code()).isEqualTo(400);
-      assertThat(ex.content()).contains(format("Organization %s cannot use private project", organizationKey));
-    }
+    expectHttpError(400,
+      format("Organization %s cannot use private project", organization.getKey()),
+      () -> tester.wsClient().organizations()
+        .updateProjectVisibility(UpdateProjectVisibilityWsRequest.builder().setOrganization(organization.getKey()).setProjectVisibility("private").build()));
   }
 
   @Test
   public void does_not_fail_to_update_project_visibility_to_private() {
-    String organizationKey = createOrganization();
-    String projectKey = createPublicProject(organizationKey);
+    String projectKey = createPublicProject();
     setServerProperty(orchestrator, "sonar.billing.preventUpdatingProjectsVisibilityToPrivate", "false");
 
-    adminClient.projects().updateVisibility(UpdateVisibilityRequest.builder().setProject(projectKey).setVisibility("private").build());
+    tester.wsClient().projects().updateVisibility(UpdateVisibilityRequest.builder().setProject(projectKey).setVisibility("private").build());
 
     assertWsResponseAsAdmin(new GetRequest("api/navigation/component").setParam("componentKey", projectKey), "\"visibility\":\"private\"");
   }
 
   @Test
   public void fail_to_update_project_visibility_to_private() {
-    String organizationKey = createOrganization();
-    String projectKey = createPublicProject(organizationKey);
+    String projectKey = createPublicProject();
     setServerProperty(orchestrator, "sonar.billing.preventUpdatingProjectsVisibilityToPrivate", "true");
 
-    try {
-      adminClient.projects().updateVisibility(UpdateVisibilityRequest.builder().setProject(projectKey).setVisibility("private").build());
-      fail();
-    } catch (HttpException ex) {
-      assertThat(ex.code()).isEqualTo(400);
-      assertThat(ex.content()).contains(format("Organization %s cannot use private project", organizationKey));
-    }
+    expectHttpError(400,
+      format("Organization %s cannot use private project", organization.getKey()),
+      () -> tester.wsClient().projects().updateVisibility(UpdateVisibilityRequest.builder().setProject(projectKey).setVisibility("private").build()));
   }
 
   @Test
   public void does_not_fail_to_create_private_project() {
-    String organizationKey = createOrganization();
     String projectKey = newProjectKey();
     setServerProperty(orchestrator, "sonar.billing.preventUpdatingProjectsVisibilityToPrivate", "false");
 
-    adminClient.projects().create(CreateRequest.builder().setKey(projectKey).setName(projectKey).setOrganization(organizationKey).setVisibility("public").build());
+    tester.wsClient().projects().create(CreateRequest.builder().setKey(projectKey).setName(projectKey).setOrganization(organization.getKey()).setVisibility("public").build());
 
     assertWsResponseAsAdmin(new GetRequest("api/navigation/component").setParam("componentKey", projectKey), "\"visibility\":\"public\"");
   }
 
   @Test
   public void fail_to_create_private_project() {
-    String organizationKey = createOrganization();
     String projectKey = newProjectKey();
     setServerProperty(orchestrator, "sonar.billing.preventUpdatingProjectsVisibilityToPrivate", "true");
 
-    try {
-      adminClient.projects().create(CreateRequest.builder().setKey(projectKey).setName(projectKey).setOrganization(organizationKey).setVisibility("private").build());
-      fail();
-    } catch (HttpException ex) {
-      assertThat(ex.code()).isEqualTo(400);
-      assertThat(ex.content()).contains(format("Organization %s cannot use private project", organizationKey));
-    }
+    expectHttpError(400,
+      format("Organization %s cannot use private project", organization.getKey()),
+      () -> tester.wsClient().projects()
+        .create(CreateRequest.builder().setKey(projectKey).setName(projectKey).setOrganization(organization.getKey()).setVisibility("private").build()));
   }
 
   @Test
   public void ui_does_not_allow_to_turn_project_to_private() {
-    String projectKey = createPublicProject(createOrganization());
+    String projectKey = createPublicProject();
     setServerProperty(orchestrator, "sonar.billing.preventUpdatingProjectsVisibilityToPrivate", "true");
 
-    nav.logIn().submitCredentials(adminUser).openProjectPermissions(projectKey)
+    Navigation.create(orchestrator)
+      .logIn().submitCredentials(orgAdministrator.getLogin())
+      .openProjectPermissions(projectKey)
       .shouldBePublic()
       .shouldNotAllowPrivate();
   }
 
   @Test
   public void ui_allows_to_turn_project_to_private() {
-    String projectKey = createPublicProject(createOrganization());
+    String projectKey = createPublicProject();
     setServerProperty(orchestrator, "sonar.billing.preventUpdatingProjectsVisibilityToPrivate", "false");
 
-    nav.logIn().submitCredentials(adminUser).openProjectPermissions(projectKey)
+    tester.openBrowser()
+      .logIn().submitCredentials(orgAdministrator.getLogin())
+      .openProjectPermissions(projectKey)
       .shouldBePublic()
       .turnToPrivate();
   }
 
-  private String createOrganization() {
-    String key = newOrganizationKey();
-    adminClient.organizations().create(new CreateWsRequest.Builder().setKey(key).setName(key).build()).getOrganization();
-    return key;
-  }
-
-  private static String createPublicProject(String organizationKey) {
+  private String createPublicProject() {
     String projectKey = newProjectKey();
-    adminClient.projects().create(CreateRequest.builder().setKey(projectKey).setName(projectKey).setOrganization(organizationKey).setVisibility("public").build());
+    tester.wsClient().projects().create(CreateRequest.builder()
+      .setKey(projectKey)
+      .setName(projectKey)
+      .setOrganization(organization.getKey())
+      .setVisibility("public")
+      .build());
     return projectKey;
   }
 
-  private String executeAnalysis(String organizationKey) {
-    return executeAnalysis(newProjectKey(), organizationKey);
-  }
-
-  private String executeAnalysis(String projectKey, String organizationKey) {
+  private String executeAnalysis(String projectKey) {
     BuildResult buildResult = orchestrator.executeBuild(SonarScanner.create(projectDir("shared/xoo-sample"),
-      "sonar.organization", organizationKey,
+      "sonar.organization", organization.getKey(),
       "sonar.projectKey", projectKey,
-      "sonar.login", adminUser,
-      "sonar.password", adminUser));
+      "sonar.login", orgAdministrator.getLogin(),
+      "sonar.password", orgAdministrator.getLogin()));
     return ItUtils.extractCeTaskId(buildResult);
   }
 
   private void assertWsResponseAsAdmin(GetRequest request, String expectedContent) {
-    WsResponse response = adminClient.wsConnector().call(request).failIfNotSuccessful();
+    WsResponse response = tester.wsClient().wsConnector().call(request).failIfNotSuccessful();
     assertThat(response.content()).contains(expectedContent);
   }
 
-  private void assertWsResponseAsUser(GetRequest request, String expectedContent) {
-    WsResponse response = newUserWsClient(orchestrator, USER_LOGIN, USER_LOGIN).wsConnector().call(request).failIfNotSuccessful();
+  private void assertWsResponseAsUser(GetRequest request, String expectedContent, User user) {
+    WsResponse response = newUserWsClient(orchestrator, user.getLogin(), user.getLogin()).wsConnector().call(request).failIfNotSuccessful();
     assertThat(response.content()).contains(expectedContent);
   }
 }
index 19dd64ec7fd48e1971dc87afc57d0f10d89613e9..3f71e96d99e65ce871d74820d7def7ea798d93f6 100644 (file)
@@ -28,41 +28,27 @@ import org.junit.ClassRule;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.rules.ExpectedException;
-import org.junit.rules.RuleChain;
-import org.junit.rules.TestRule;
+import org.sonarqube.test.Tester;
 import org.sonarqube.ws.Organizations.Organization;
 import org.sonarqube.ws.WsUsers.CreateWsResponse.User;
 import org.sonarqube.ws.client.HttpException;
-import org.sonarqube.ws.client.WsClient;
 import org.sonarqube.ws.client.permission.AddUserWsRequest;
-import pageobjects.Navigation;
-import util.OrganizationRule;
-import util.user.UserRule;
 
-import static util.ItUtils.newAdminWsClient;
 import static util.ItUtils.setServerProperty;
 
 public class OrganizationMembershipTest {
 
-  private static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
-  private static OrganizationRule organizations = new OrganizationRule(orchestrator);
-  private static UserRule users = new UserRule(orchestrator);
-  private static Navigation nav = Navigation.get(orchestrator);
-
   @ClassRule
-  public static TestRule chain = RuleChain.outerRule(orchestrator)
-    .around(users)
-    .around(organizations)
-    .around(nav);
+  public static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
 
   @Rule
-  public ExpectedException expectedException = ExpectedException.none();
+  public Tester tester = new Tester(orchestrator);
 
-  private static WsClient adminClient;
+  @Rule
+  public ExpectedException expectedException = ExpectedException.none();
 
   @BeforeClass
   public static void setUp() {
-    adminClient = newAdminWsClient(orchestrator);
     setServerProperty(orchestrator, "sonar.organizations.anyoneCanCreate", "true");
   }
 
@@ -73,45 +59,45 @@ public class OrganizationMembershipTest {
 
   @Test
   public void new_user_should_not_become_member_of_default_organization() {
-    User user = users.createUser();
-    organizations.assertThatNotMemberOf(null, user);
+    User user = tester.users().generate();
+    tester.organizations().assertThatNotMemberOf(null, user);
   }
 
   @Test
   public void add_and_remove_member() {
-    Organization organization = organizations.create();
-    User user = users.createUser();
+    Organization organization = tester.organizations().generate();
+    User user = tester.users().generate();
 
     addMembership(organization, user);
-    organizations.assertThatMemberOf(organization, user);
+    tester.organizations().assertThatMemberOf(organization, user);
 
     removeMembership(organization, user);
-    organizations.assertThatNotMemberOf(organization, user);
+    tester.organizations().assertThatNotMemberOf(organization, user);
   }
 
   @Test
   public void remove_organization_admin_member() {
-    Organization organization = organizations.create();
-    User user = users.createUser();
+    Organization organization = tester.organizations().generate();
+    User user = tester.users().generate();
     addMembership(organization, user);
 
-    adminClient.permissions().addUser(new AddUserWsRequest().setLogin(user.getLogin()).setPermission("admin").setOrganization(organization.getKey()));
-    organizations.assertThatMemberOf(organization, user);
+    tester.wsClient().permissions().addUser(new AddUserWsRequest().setLogin(user.getLogin()).setPermission("admin").setOrganization(organization.getKey()));
+    tester.organizations().assertThatMemberOf(organization, user);
 
     removeMembership(organization, user);
-    organizations.assertThatNotMemberOf(organization, user);
+    tester.organizations().assertThatNotMemberOf(organization, user);
   }
 
   @Test
   public void fail_to_remove_organization_admin_member_when_last_admin() {
-    Organization organization = organizations.create();
-    User user = users.createUser();
+    Organization organization = tester.organizations().generate();
+    User user = tester.users().generate();
     addMembership(organization, user);
 
-    adminClient.permissions().addUser(new AddUserWsRequest().setLogin(user.getLogin()).setPermission("admin").setOrganization(organization.getKey()));
-    organizations.assertThatMemberOf(organization, user);
+    tester.wsClient().permissions().addUser(new AddUserWsRequest().setLogin(user.getLogin()).setPermission("admin").setOrganization(organization.getKey()));
+    tester.organizations().assertThatMemberOf(organization, user);
     // Admin is the creator of the organization so he was granted with admin permission
-    adminClient.organizations().removeMember(organization.getKey(), "admin");
+    tester.wsClient().organizations().removeMember(organization.getKey(), "admin");
 
     expectedException.expect(HttpException.class);
     expectedException.expectMessage("The last administrator member cannot be removed");
@@ -120,29 +106,28 @@ public class OrganizationMembershipTest {
 
   @Test
   public void remove_user_remove_its_membership() {
-    Organization organization = organizations.create();
-    User user = users.createUser();
+    Organization organization = tester.organizations().generate();
+    User user = tester.users().generate();
     addMembership(organization, user);
 
-    users.deactivateUsers(user.getLogin());
-    organizations.assertThatNotMemberOf(organization, user);
+    tester.users().service().deactivate(user.getLogin());
+    tester.organizations().assertThatNotMemberOf(organization, user);
   }
 
   @Test
   public void user_creating_an_organization_becomes_member_of_this_organization() {
-    String password = "aPassword";
-    User user = users.createUser(p -> p.setPassword(password));
+    User user = tester.users().generate();
 
-    Organization organization = organizations.as(user.getLogin(), password).create();
+    Organization organization = tester.as(user.getLogin()).organizations().generate();
 
-    organizations.assertThatMemberOf(organization, user);
+    tester.organizations().assertThatMemberOf(organization, user);
   }
 
   private void addMembership(Organization organization, User user) {
-    adminClient.organizations().addMember(organization.getKey(), user.getLogin());
+    tester.organizations().addMember(organization, user);
   }
 
   private void removeMembership(Organization organization, User user) {
-    adminClient.organizations().removeMember(organization.getKey(), user.getLogin());
+    tester.wsClient().organizations().removeMember(organization.getKey(), user.getLogin());
   }
 }
index 702475a3b23ec1716d5003b637693a32821521b2..8f39de54af8d39a9b5359d8fb6f629b5cd4ce37e 100644 (file)
@@ -23,74 +23,50 @@ package it.organization;
 import com.sonar.orchestrator.Orchestrator;
 import it.Category6Suite;
 import org.junit.After;
-import org.junit.AfterClass;
 import org.junit.Before;
-import org.junit.BeforeClass;
 import org.junit.ClassRule;
 import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.RuleChain;
-import org.junit.rules.TestRule;
+import org.sonarqube.test.OrganizationTester;
+import org.sonarqube.test.Tester;
 import org.sonarqube.ws.Organizations.Organization;
 import org.sonarqube.ws.WsUsers.CreateWsResponse.User;
-import org.sonarqube.ws.client.WsClient;
-import pageobjects.Navigation;
 import pageobjects.organization.MembersPage;
-import util.OrganizationRule;
-import util.user.UserRule;
 
-import static util.ItUtils.newAdminWsClient;
 import static util.ItUtils.setServerProperty;
 
 public class OrganizationMembershipUiTest {
 
-  private static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
-  private static OrganizationRule organizations = new OrganizationRule(orchestrator);
-  private static UserRule users = new UserRule(orchestrator);
-
   @ClassRule
-  public static TestRule chain = RuleChain.outerRule(orchestrator)
-    .around(users)
-    .around(organizations);
+  public static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
 
   @Rule
-  public Navigation nav = Navigation.get(orchestrator);
+  public Tester tester = new Tester(orchestrator);
 
-  private static WsClient rootWsClient;
-  private String adminUser;
-
-  @BeforeClass
-  public static void setUp() {
-    rootWsClient = newAdminWsClient(orchestrator);
-    setServerProperty(orchestrator, "sonar.organizations.anyoneCanCreate", "true");
-  }
-
-  @AfterClass
-  public static void tearDown() {
-    setServerProperty(orchestrator, "sonar.organizations.anyoneCanCreate", null);
-  }
+  private User root;
 
   @Before
-  public void createRootUser() {
-    adminUser = users.createRootUser();
+  public void setUp() {
+    setServerProperty(orchestrator, "sonar.organizations.anyoneCanCreate", "true");
+    root = tester.users().generate();
+    tester.wsClient().roots().setRoot(root.getLogin());
   }
 
   @After
-  public void purgeData() throws Exception {
-    organizations.deleteOrganizations();
-    users.deactivateAllUsers();
+  public void tearDown() {
+    setServerProperty(orchestrator, "sonar.organizations.anyoneCanCreate", null);
   }
 
   @Test
   public void should_display_members_page() {
-    Organization organization = organizations.create();
-    User member1 = users.createUser(p -> p.setName("foo"));
-    addMembership(organization, member1);
-    User member2 = users.createUser(p -> p.setName("bar"));
-    addMembership(organization, member2);
-    users.createUser();
-
-    MembersPage page = nav.openOrganizationMembers(organization.getKey());
+    Organization organization = tester.organizations().generate();
+    User member1 = tester.users().generate(p -> p.setName("foo"));
+    addMember(organization, member1);
+    User member2 = tester.users().generate(p -> p.setName("bar"));
+    addMember(organization, member2);
+    User nonMember = tester.users().generate();
+
+    MembersPage page = tester.openBrowser().openOrganizationMembers(organization.getKey());
     page
       .canNotAddMember()
       .shouldHaveTotal(3);
@@ -104,56 +80,53 @@ public class OrganizationMembershipUiTest {
 
   @Test
   public void search_for_members() {
-    Organization organization = organizations.create();
-
-    User user1 = users.createUser();
-    rootWsClient.organizations().addMember(organization.getKey(), user1.getLogin());
-
-    User user2 = users.createUser(p -> p.setLogin("sameprefixuser1"));
-    rootWsClient.organizations().addMember(organization.getKey(), user2.getLogin());
-
+    Organization organization = tester.organizations().generate();
+    User member1 = tester.users().generate(p -> p.setName("foo"));
+    addMember(organization, member1);
+    User member2 = tester.users().generate(p -> p.setName("sameprefixuser1"));
+    addMember(organization, member2);
     // Created to verify that only the user part of the org is returned
-    users.createUser(p -> p.setLogin("sameprefixuser2"));
+    User userWithSameNamePrefix = tester.users().generate(p -> p.setName(member2.getName() + "sameprefixuser2"));
 
-    MembersPage page = nav.openOrganizationMembers(organization.getKey());
+    MembersPage page = tester.openBrowser().openOrganizationMembers(organization.getKey());
     page
       .searchForMember("sameprefixuser")
       .shouldHaveTotal(1);
-    page.getMembersByIdx(0).shouldBeNamed(user2.getLogin(), user2.getName());
+    page.getMembersByIdx(0).shouldBeNamed(member2.getLogin(), member2.getName());
     page
-      .searchForMember(user1.getLogin())
+      .searchForMember(member1.getLogin())
       .shouldHaveTotal(1);
-    page.getMembersByIdx(0).shouldBeNamed(user1.getLogin(), user1.getName());
+    page.getMembersByIdx(0).shouldBeNamed(member1.getLogin(), member1.getName());
   }
 
   @Test
   public void admin_can_add_members() {
-    Organization organization = organizations.create();
-    String orgKey = organization.getKey();
-    User user = users.createUser(p -> p.setLogin("foo"));
-    users.createUser();
+    Organization organization = tester.organizations().generate();
+    User user1 = tester.users().generate(u -> u.setLogin("foo"));
+    User user2 = tester.users().generate();
 
-    MembersPage page = nav.logIn().submitCredentials(adminUser).openOrganizationMembers(orgKey);
+    MembersPage page = tester.openBrowser()
+      .logIn().submitCredentials(root.getLogin())
+      .openOrganizationMembers(organization.getKey());
     page
       .shouldHaveTotal(1)
-      .addMember(user.getLogin())
+      .addMember(user1.getLogin())
       .shouldHaveTotal(2);
     page.getMembersByIdx(0).shouldBeNamed("admin", "Administrator").shouldHaveGroups(2);
-    page.getMembersByIdx(1).shouldBeNamed(user.getLogin(), user.getName()).shouldHaveGroups(1);
+    page.getMembersByIdx(1).shouldBeNamed(user1.getLogin(), user1.getName()).shouldHaveGroups(1);
   }
 
   @Test
   public void admin_can_remove_members() {
-    Organization organization = organizations.create();
-    String orgKey = organization.getKey();
-
-    User user1 = users.createUser();
-    rootWsClient.organizations().addMember(orgKey, user1.getLogin());
-
-    User user2 = users.createUser();
-    rootWsClient.organizations().addMember(orgKey, user2.getLogin());
-
-    MembersPage page = nav.logIn().submitCredentials(adminUser).openOrganizationMembers(orgKey);
+    Organization organization = tester.organizations().generate();
+    User user1 = tester.users().generate();
+    addMember(organization, user1);
+    User user2 = tester.users().generate();
+    addMember(organization, user2);
+
+    MembersPage page = tester.openBrowser()
+      .logIn().submitCredentials(root.getLogin())
+      .openOrganizationMembers(organization.getKey());
     page.shouldHaveTotal(3)
       .getMembersByIdx(1).removeMembership();
     page.shouldHaveTotal(2);
@@ -161,13 +134,13 @@ public class OrganizationMembershipUiTest {
 
   @Test
   public void admin_can_manage_groups() {
-    Organization organization = organizations.create();
-    String orgKey = organization.getKey();
-
-    User user = users.createUser(p -> p.setLogin("foo"));
-    rootWsClient.organizations().addMember(orgKey, user.getLogin());
+    Organization organization = tester.organizations().generate();
+    User user = tester.users().generate(u -> u.setLogin("foo"));
+    addMember(organization, user);
 
-    MembersPage page = nav.logIn().submitCredentials(adminUser).openOrganizationMembers(orgKey);
+    MembersPage page = tester.openBrowser()
+      .logIn().submitCredentials(root.getLogin())
+      .openOrganizationMembers(organization.getKey());
     // foo user
     page.getMembersByIdx(1)
       .manageGroupsOpen()
@@ -184,11 +157,12 @@ public class OrganizationMembershipUiTest {
 
   @Test
   public void groups_count_should_be_updated_when_a_member_was_just_added() {
-    Organization organization = organizations.create();
-    String orgKey = organization.getKey();
-    User user = users.createUser(p -> p.setLogin("foo"));
+    Organization organization = tester.organizations().generate();
+    User user = tester.users().generate();
 
-    MembersPage page = nav.logIn().submitCredentials(adminUser).openOrganizationMembers(orgKey);
+    MembersPage page = tester.openBrowser()
+      .logIn().submitCredentials(root.getLogin())
+      .openOrganizationMembers(organization.getKey());
     page
       .addMember(user.getLogin())
       .getMembersByIdx(1)
@@ -199,7 +173,7 @@ public class OrganizationMembershipUiTest {
       .shouldHaveGroups(2);
   }
 
-  private void addMembership(Organization organization, User user) {
-    rootWsClient.organizations().addMember(organization.getKey(), user.getLogin());
+  private OrganizationTester addMember(Organization organization, User member1) {
+    return tester.organizations().addMember(organization, member1);
   }
 }
index 4f6c15bf0a03faac556f07e354b18af732e640fe..fcde79399e2d727e5ca2f43606a52b49e9cddee0 100644 (file)
@@ -29,30 +29,24 @@ import org.junit.ClassRule;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.rules.ExpectedException;
-import org.sonarqube.ws.Organizations;
+import org.sonarqube.test.OrganizationTester;
+import org.sonarqube.test.Tester;
 import org.sonarqube.ws.Organizations.Organization;
 import org.sonarqube.ws.QualityProfiles;
 import org.sonarqube.ws.Rules;
 import org.sonarqube.ws.WsComponents;
+import org.sonarqube.ws.WsUserGroups.Group;
 import org.sonarqube.ws.WsUsers;
 import org.sonarqube.ws.WsUsers.CreateWsResponse.User;
-import org.sonarqube.ws.client.PostRequest;
-import org.sonarqube.ws.client.WsClient;
 import org.sonarqube.ws.client.component.ComponentsService;
 import org.sonarqube.ws.client.organization.CreateWsRequest;
+import org.sonarqube.ws.client.organization.OrganizationService;
 import org.sonarqube.ws.client.organization.SearchWsRequest;
 import org.sonarqube.ws.client.organization.UpdateWsRequest;
 import org.sonarqube.ws.client.permission.AddUserWsRequest;
 import org.sonarqube.ws.client.permission.PermissionsService;
-import org.sonarqube.ws.client.user.GroupsRequest;
-import util.OrganizationRule;
-import util.OrganizationSupport;
-import util.user.GroupManagement;
-import util.user.Groups;
-import util.user.UserRule;
 
 import static java.util.Collections.singletonList;
-import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.junit.Assert.fail;
 import static util.ItUtils.expectBadRequestError;
@@ -74,19 +68,14 @@ public class OrganizationTest {
   private static final String DESCRIPTION = "the description of Foo company";
   private static final String URL = "https://www.foo.fr";
   private static final String AVATAR_URL = "https://www.foo.fr/corporate_logo.png";
-  private static final String USER_LOGIN = "foo";
 
   @ClassRule
   public static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
   @Rule
-  public OrganizationRule organizations = new OrganizationRule(orchestrator);
-  @Rule
-  public UserRule users = new UserRule(orchestrator);
+  public Tester tester = new Tester(orchestrator);
   @Rule
   public ExpectedException expectedException = ExpectedException.none();
 
-  private WsClient adminClient = newAdminWsClient(orchestrator);
-
   @After
   public void tearDown() {
     setServerProperty(orchestrator, SETTING_ANYONE_CAN_CREATE_ORGANIZATIONS, null);
@@ -94,24 +83,26 @@ public class OrganizationTest {
 
   @Test
   public void default_organization_should_exist() {
-    Organization defaultOrg = organizations.getWsService().search(SearchWsRequest.builder().build())
+    Organization defaultOrg = tester.organizations().service().search(SearchWsRequest.builder().build())
       .getOrganizationsList()
       .stream()
       .filter(Organization::getGuarded)
       .findFirst()
       .orElseThrow(IllegalStateException::new);
-    assertThat(defaultOrg.getKey().equals(DEFAULT_ORGANIZATION_KEY));
-    assertThat(defaultOrg.getName().equals("Default Organization"));
+    assertThat(defaultOrg.getKey()).isEqualTo(DEFAULT_ORGANIZATION_KEY);
+    assertThat(defaultOrg.getName()).isEqualTo("Default Organization");
   }
 
   @Test
   public void default_organization_can_not_be_deleted() {
-    expectBadRequestError(() -> organizations.getWsService().delete(DEFAULT_ORGANIZATION_KEY));
+    expectBadRequestError(() -> tester.organizations().service().delete(DEFAULT_ORGANIZATION_KEY));
   }
 
   @Test
   public void create_update_and_delete_organizations() {
-    Organization org = organizations.create(o -> o
+    OrganizationService service = tester.organizations().service();
+
+    Organization org = tester.organizations().generate(o -> o
       .setName(NAME)
       .setDescription(DESCRIPTION)
       .setUrl(URL)
@@ -126,7 +117,7 @@ public class OrganizationTest {
     assertThatBuiltInQualityProfilesExist(org);
 
     // update by key
-    organizations.getWsService().update(new UpdateWsRequest.Builder()
+    service.update(new UpdateWsRequest.Builder()
       .setKey(org.getKey())
       .setName("new name")
       .setDescription("new description")
@@ -136,7 +127,7 @@ public class OrganizationTest {
     verifyOrganization(org, "new name", "new description", "new url", "new avatar url");
 
     // remove optional fields
-    organizations.getWsService().update(new UpdateWsRequest.Builder()
+    service.update(new UpdateWsRequest.Builder()
       .setKey(org.getKey())
       .setName("new name 2")
       .setDescription("")
@@ -146,12 +137,12 @@ public class OrganizationTest {
     verifyOrganization(org, "new name 2", null, null, null);
 
     // delete organization
-    organizations.delete(org);
+    service.delete(org.getKey());
     assertThatOrganizationDoesNotExit(org);
     assertThatQualityProfilesDoNotExist(org);
 
     // create again
-    organizations.getWsService().create(new CreateWsRequest.Builder()
+    service.create(new CreateWsRequest.Builder()
       .setName(NAME)
       .setKey(org.getKey())
       .build())
@@ -164,7 +155,7 @@ public class OrganizationTest {
     // create organization without key
     String name = "Foo  Company to keyize";
     String expectedKey = "foo-company-to-keyize";
-    Organization createdOrganization = organizations.getWsService().create(new CreateWsRequest.Builder()
+    Organization createdOrganization = tester.organizations().service().create(new CreateWsRequest.Builder()
       .setName(name)
       .build())
       .getOrganization();
@@ -174,63 +165,60 @@ public class OrganizationTest {
 
   @Test
   public void anonymous_user_cannot_administrate_organization() {
-    Organization org = organizations.create();
-    OrganizationSupport anonymousOrganisations = organizations.asAnonymous();
+    Organization org = tester.organizations().generate();
+    OrganizationTester anonymousTester = tester.asAnonymous().organizations();
 
-    expectForbiddenError(() -> anonymousOrganisations.create());
-    expectUnauthorizedError(() -> anonymousOrganisations.getWsService().update(new UpdateWsRequest.Builder().setKey(org.getKey()).setName("new name").build()));
-    expectUnauthorizedError(() -> anonymousOrganisations.delete(org));
+    expectForbiddenError(() -> anonymousTester.generate());
+    expectUnauthorizedError(() -> anonymousTester.service().update(new UpdateWsRequest.Builder().setKey(org.getKey()).setName("new name").build()));
+    expectUnauthorizedError(() -> anonymousTester.service().delete(org.getKey()));
   }
 
   @Test
   public void logged_in_user_cannot_administrate_organization() {
-    Organization org = organizations.create();
-    String password = "aPassword";
-    User user = users.createUser(p -> p.setPassword(password));
-    OrganizationSupport userOrganisations = organizations.as(user.getLogin(), password);
-
-    expectForbiddenError(() -> userOrganisations.create());
-    expectForbiddenError(() -> userOrganisations.getWsService().update(new UpdateWsRequest.Builder().setKey(org.getKey()).setName("new name").build()));
-    expectForbiddenError(() -> userOrganisations.delete(org));
+    Organization org = tester.organizations().generate();
+    User user = tester.users().generate();
+    OrganizationTester userTester = tester.as(user.getLogin()).organizations();
+
+    expectForbiddenError(() -> userTester.generate());
+    expectForbiddenError(() -> userTester.service().update(new UpdateWsRequest.Builder().setKey(org.getKey()).setName("new name").build()));
+    expectForbiddenError(() -> userTester.service().delete(org.getKey()));
   }
 
   @Test
   public void logged_in_user_can_administrate_organization_if_root() {
-    String password = "aPassword";
-    User user = users.createUser(p -> p.setPassword(password));
-    OrganizationSupport userOrganisations = organizations.as(user.getLogin(), password);
+    User user = tester.users().generate();
+    OrganizationTester asUser = tester.as(user.getLogin()).organizations();
 
-    users.setRoot(user.getLogin());
-    Organization org = userOrganisations.create();
+    tester.wsClient().roots().setRoot(user.getLogin());
+    Organization org = asUser.generate();
 
     // delete org, attempt recreate when no root anymore and ensure it can't anymore
-    userOrganisations.delete(org);
+    asUser.service().delete(org.getKey());
 
-    users.unsetRoot(user.getLogin());
-    expectForbiddenError(() -> userOrganisations.create());
+    tester.wsClient().roots().unsetRoot(user.getLogin());
+    expectForbiddenError(() -> asUser.generate());
   }
 
   @Test
   public void an_organization_member_can_analyze_project() {
-    Organization organization = organizations.create();
-
-    String password = "aPassword";
-    User user = users.createUser(p -> p.setPassword(password));
-    users.removeGroups("sonar-users");
-    organizations.getWsService().addMember(organization.getKey(), user.getLogin());
+    Organization organization = tester.organizations().generate();
+    User user = tester.users().generate();
+    Group group = tester.groups().generate(organization);
+    // users.removeGroups("sonar-users");
+    tester.organizations().service().addMember(organization.getKey(), user.getLogin());
     addPermissionsToUser(organization.getKey(), user.getLogin(), "provisioning", "scan");
 
     runProjectAnalysis(orchestrator, "shared/xoo-sample",
       "sonar.organization", organization.getKey(),
       "sonar.login", user.getLogin(),
-      "sonar.password", password);
-    ComponentsService componentsService = newUserWsClient(orchestrator, user.getLogin(), password).components();
+      "sonar.password", user.getLogin());
+    ComponentsService componentsService = newUserWsClient(orchestrator, user.getLogin(), user.getLogin()).components();
     assertThat(searchSampleProject(organization.getKey(), componentsService).getComponentsList()).hasSize(1);
   }
 
   @Test
   public void by_default_anonymous_cannot_analyse_project_on_organization() {
-    Organization organization = organizations.create();
+    Organization organization = tester.organizations().generate();
 
     try {
       runProjectAnalysis(orchestrator, "shared/xoo-sample",
@@ -246,7 +234,7 @@ public class OrganizationTest {
 
   @Test
   public void by_default_anonymous_can_browse_project_on_organization() {
-    Organization organization = organizations.create();
+    Organization organization = tester.organizations().generate();
 
     runProjectAnalysis(orchestrator, "shared/xoo-sample", "sonar.organization", organization.getKey(), "sonar.login", "admin", "sonar.password", "admin");
 
@@ -263,27 +251,17 @@ public class OrganizationTest {
   }
 
   @Test
-  public void deleting_an_organization_also_deletes_projects() {
-    Organization organization = organizations.create();
-
-    GroupManagement groupManagement = users.forOrganization(organization.getKey());
-
-    users.createUser(USER_LOGIN, USER_LOGIN);
-    organizations.getWsService().addMember(organization.getKey(), USER_LOGIN);
-    groupManagement.createGroup("grp1");
-    groupManagement.createGroup("grp2");
-    groupManagement.associateGroupsToUser(USER_LOGIN, "grp1", "grp2");
-    assertThat(groupManagement.getUserGroups(USER_LOGIN).getGroups())
-      .extracting(Groups.Group::getName)
-      .contains("grp1", "grp2");
-    addPermissionsToUser(organization.getKey(), USER_LOGIN, "provisioning", "scan");
+  public void deleting_an_organization_deletes_its_projects() {
+    Organization organization = tester.organizations().generate();
 
     runProjectAnalysis(orchestrator, "shared/xoo-sample",
-      "sonar.organization", organization.getKey(), "sonar.login", USER_LOGIN, "sonar.password", USER_LOGIN);
-    ComponentsService componentsService = newAdminWsClient(orchestrator).components();
+      "sonar.organization", organization.getKey(),
+      "sonar.login", "admin",
+      "sonar.password", "admin");
+    ComponentsService componentsService = tester.wsClient().components();
     assertThat(searchSampleProject(organization.getKey(), componentsService).getComponentsList()).hasSize(1);
 
-    organizations.delete(organization);
+    tester.organizations().service().delete(organization.getKey());
 
     expectNotFoundError(() -> searchSampleProject(organization.getKey(), componentsService));
     assertThatOrganizationDoesNotExit(organization);
@@ -291,45 +269,41 @@ public class OrganizationTest {
 
   @Test
   public void return_groups_belonging_to_a_user_on_an_organization() throws Exception {
-    String userLogin = randomAlphabetic(10);
-    String groupName = randomAlphabetic(10);
-    Organization organization = organizations.create();
-    users.createUser(userLogin, userLogin);
-    organizations.getWsService().addMember(organization.getKey(), userLogin);
-    adminClient.wsConnector().call(new PostRequest("api/user_groups/create")
-      .setParam("name", groupName)
-      .setParam("description", groupName)
-      .setParam("organization", organization.getKey())).failIfNotSuccessful();
-    adminClient.wsConnector().call(new PostRequest("api/user_groups/add_user")
-      .setParam("login", userLogin)
-      .setParam("name", groupName)
-      .setParam("organization", organization.getKey())).failIfNotSuccessful();
-
-    List<WsUsers.GroupsWsResponse.Group> result = adminClient.users().groups(
-      GroupsRequest.builder().setLogin(userLogin).setOrganization(organization.getKey()).build()).getGroupsList();
-
-    assertThat(result).extracting(WsUsers.GroupsWsResponse.Group::getName).containsOnly(groupName, "Members");
+    Organization organization = tester.organizations().generate();
+    User user = tester.users().generate();
+    tester.organizations().service().addMember(organization.getKey(), user.getLogin());
+
+    Group group = tester.groups().generate(organization);
+    tester.groups().addMemberToGroups(organization, user.getLogin(), group.getName());
+
+    List<WsUsers.GroupsWsResponse.Group> memberOfGroups = tester.groups().getGroupsOfUser(organization, user.getLogin());
+
+    assertThat(memberOfGroups).extracting(WsUsers.GroupsWsResponse.Group::getName)
+      .containsExactlyInAnyOrder(group.getName(), "Members");
   }
 
   @Test
   public void anonymous_cannot_create_organizations_even_if_anyone_is_allowed_to() {
     setServerProperty(orchestrator, SETTING_ANYONE_CAN_CREATE_ORGANIZATIONS, "true");
 
-    expectUnauthorizedError(() -> organizations.asAnonymous().create());
+    expectUnauthorizedError(() -> tester.asAnonymous().organizations().generate());
   }
 
   @Test
   public void logged_in_user_can_create_organizations_if_anyone_is_allowed_to() {
     setServerProperty(orchestrator, SETTING_ANYONE_CAN_CREATE_ORGANIZATIONS, "true");
+    User user = tester.users().generate();
+
+    Organization organization = tester.as(user.getLogin()).organizations().generate();
 
-    String password = "aPassword";
-    User user = users.createUser(p -> p.setPassword(password));
-    OrganizationSupport userOrganisations = organizations.as(user.getLogin(), password);
-    Organizations.Organization org = userOrganisations.create();
+    assertThat(organization.getName()).isNotEmpty();
+    assertThat(organization.getKey()).isNotEmpty();
+    assertThat(organization.getGuarded()).isFalse();
 
-    assertThat(org.getName()).isNotEmpty();
-    assertThat(org.getKey()).isNotEmpty();
-    assertThat(org.getGuarded()).isFalse();
+    List<Organization> reloadedOrgs = tester.organizations().service().search(SearchWsRequest.builder().build()).getOrganizationsList();
+    assertThat(reloadedOrgs)
+      .filteredOn(o -> o.getKey().equals(organization.getKey()))
+      .hasSize(1);
   }
 
   private WsComponents.SearchWsResponse searchSampleProject(String organizationKey, ComponentsService componentsService) {
@@ -341,14 +315,14 @@ public class OrganizationTest {
   }
 
   private void assertThatOrganizationDoesNotExit(Organization org) {
-    Organizations.SearchWsResponse searchWsResponse = organizations.getWsService().search(new SearchWsRequest.Builder().setOrganizations(org.getKey()).build());
-    assertThat(searchWsResponse.getOrganizationsList()).isEmpty();
+    SearchWsRequest request = new SearchWsRequest.Builder().setOrganizations(org.getKey()).build();
+    assertThat(tester.organizations().service().search(request).getOrganizationsList()).isEmpty();
   }
 
   private void verifyOrganization(Organization createdOrganization, String name, String description, String url,
     String avatarUrl) {
-    List<Organization> result = organizations.getWsService().search(new SearchWsRequest.Builder().setOrganizations(createdOrganization.getKey())
-      .build()).getOrganizationsList();
+    SearchWsRequest request = new SearchWsRequest.Builder().setOrganizations(createdOrganization.getKey()).build();
+    List<Organization> result = tester.organizations().service().search(request).getOrganizationsList();
     assertThat(result).hasSize(1);
     Organization searchedOrganization = result.get(0);
     assertThat(searchedOrganization.getKey()).isEqualTo(createdOrganization.getKey());
@@ -373,7 +347,7 @@ public class OrganizationTest {
   private void assertThatBuiltInQualityProfilesExist(Organization org) {
     org.sonarqube.ws.client.qualityprofile.SearchWsRequest profilesRequest = new org.sonarqube.ws.client.qualityprofile.SearchWsRequest()
       .setOrganizationKey(org.getKey());
-    QualityProfiles.SearchWsResponse response = adminClient.qualityProfiles().search(profilesRequest);
+    QualityProfiles.SearchWsResponse response = tester.wsClient().qualityProfiles().search(profilesRequest);
     assertThat(response.getProfilesCount()).isGreaterThan(0);
 
     response.getProfilesList().forEach(p -> {
@@ -385,7 +359,7 @@ public class OrganizationTest {
       } else {
         assertThat(p.getActiveRuleCount()).isGreaterThan(0);
         // that allows to check the Elasticsearch index of active rules
-        Rules.SearchResponse activeRulesResponse = adminClient.rules().search(new org.sonarqube.ws.client.rule.SearchWsRequest().setActivation(true).setQProfile(p.getKey()));
+        Rules.SearchResponse activeRulesResponse = tester.wsClient().rules().search(new org.sonarqube.ws.client.rule.SearchWsRequest().setActivation(true).setQProfile(p.getKey()));
         assertThat(activeRulesResponse.getTotal()).as("profile " + p.getName()).isEqualTo(p.getActiveRuleCount());
         assertThat(activeRulesResponse.getRulesCount()).isEqualTo((int) p.getActiveRuleCount());
       }
@@ -393,7 +367,7 @@ public class OrganizationTest {
   }
 
   private void assertThatQualityProfilesDoNotExist(Organization org) {
-    expectNotFoundError(() -> adminClient.qualityProfiles().search(
+    expectNotFoundError(() -> tester.wsClient().qualityProfiles().search(
       new org.sonarqube.ws.client.qualityprofile.SearchWsRequest().setOrganizationKey(org.getKey())));
   }
 }
index 3d349f95f2a6f6a036a27690772363a3cd418433..76bf2f9eec32514c81289a63d6bc392141285202 100644 (file)
@@ -23,17 +23,15 @@ package it.organization;
 import com.sonar.orchestrator.Orchestrator;
 import it.Category6Suite;
 import java.util.List;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
+import org.junit.After;
+import org.junit.Before;
 import org.junit.ClassRule;
+import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.RuleChain;
-import org.junit.rules.TestRule;
+import org.sonarqube.test.Tester;
 import org.sonarqube.ws.Organizations;
 import org.sonarqube.ws.WsUsers;
 import org.sonarqube.ws.client.organization.SearchWsRequest;
-import util.OrganizationRule;
-import util.user.UserRule;
 
 import static org.assertj.core.api.Assertions.assertThat;
 import static util.ItUtils.setServerProperty;
@@ -42,36 +40,33 @@ public class PersonalOrganizationTest {
 
   private static final String SETTING_CREATE_PERSONAL_ORG = "sonar.organizations.createPersonalOrg";
 
-  private static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
-  private static OrganizationRule organizations = new OrganizationRule(orchestrator);
-  private static UserRule users = new UserRule(orchestrator);
-
   @ClassRule
-  public static TestRule chain = RuleChain.outerRule(orchestrator)
-    .around(users)
-    .around(organizations);
+  public static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
+
+  @Rule
+  public Tester tester = new Tester(orchestrator);
 
-  @BeforeClass
-  public static void setUp() {
+  @Before
+  public void setUp() {
     setServerProperty(orchestrator, SETTING_CREATE_PERSONAL_ORG, "true");
   }
 
-  @AfterClass
-  public static void tearDown() {
+  @After
+  public void tearDown() {
     setServerProperty(orchestrator, SETTING_CREATE_PERSONAL_ORG, null);
   }
 
   @Test
   public void personal_organizations_are_created_for_new_users() {
-    WsUsers.CreateWsResponse.User user = users.createUser();
+    WsUsers.CreateWsResponse.User user = tester.users().generate();
 
-    List<Organizations.Organization> existing = organizations.getWsService().search(SearchWsRequest.builder().build()).getOrganizationsList();
+    List<Organizations.Organization> existing = tester.wsClient().organizations().search(SearchWsRequest.builder().build()).getOrganizationsList();
     assertThat(existing)
       .filteredOn(o -> o.getGuarded())
       .filteredOn(o -> o.getKey().equals(user.getLogin()))
       .hasSize(1)
       .matches(l -> l.get(0).getName().equals(user.getName()));
 
-    organizations.assertThatMemberOf(existing.get(0), user);
+    tester.organizations().assertThatMemberOf(existing.get(0), user);
   }
 }
index 1e674c12f3efa1577772ed644add7236216d6dca..75c66ba02dfa694abc2320fee14908224fdfa387 100644 (file)
@@ -25,74 +25,67 @@ import java.sql.SQLException;
 import org.junit.ClassRule;
 import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.RuleChain;
-import org.junit.rules.TestRule;
+import org.sonarqube.test.Session;
+import org.sonarqube.test.Tester;
 import org.sonarqube.ws.WsRoot;
-import org.sonarqube.ws.client.WsClient;
-import util.OrganizationRule;
+import org.sonarqube.ws.WsUsers;
 import util.user.UserRule;
 
 import static org.assertj.core.api.Assertions.assertThat;
 import static util.ItUtils.expectBadRequestError;
 import static util.ItUtils.expectForbiddenError;
-import static util.ItUtils.newAdminWsClient;
-import static util.ItUtils.newUserWsClient;
 
 public class RootUserOnOrganizationTest {
 
-  private static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
-  private static OrganizationRule organizationRule = new OrganizationRule(orchestrator);
-
   @ClassRule
-  public static TestRule chain = RuleChain.outerRule(orchestrator)
-    .around(organizationRule);
+  public static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
 
   @Rule
-  public UserRule userRule = UserRule.from(orchestrator);
+  public Tester tester = new Tester(orchestrator);
 
   @Test
   public void system_administrator_is_flagged_as_root_when_he_enables_organization_support() {
-    assertThat(newAdminWsClient(orchestrator).rootService().search().getRootsList())
+    assertThat(tester.wsClient().roots().search().getRootsList())
       .extracting(WsRoot.Root::getLogin)
       .containsExactly(UserRule.ADMIN_LOGIN);
   }
 
   @Test
   public void a_root_can_flag_other_user_as_root() {
-    userRule.createUser("bar", "foo");
-    userRule.setRoot("bar");
+    WsUsers.CreateWsResponse.User user = tester.users().generate();
+    tester.wsClient().roots().setRoot(user.getLogin());
 
-    assertThat(newAdminWsClient(orchestrator).rootService().search().getRootsList())
+    assertThat(tester.wsClient().roots().search().getRootsList())
       .extracting(WsRoot.Root::getLogin)
-      .containsOnly(UserRule.ADMIN_LOGIN, "bar");
+      .containsExactlyInAnyOrder(UserRule.ADMIN_LOGIN, user.getLogin());
   }
 
   @Test
   public void last_root_can_not_be_unset_root() throws SQLException {
-    expectBadRequestError(() -> newAdminWsClient(orchestrator).rootService().unsetRoot(UserRule.ADMIN_LOGIN));
+    expectBadRequestError(() -> tester.wsClient().roots().unsetRoot(UserRule.ADMIN_LOGIN));
   }
 
   @Test
   public void root_can_be_set_and_unset_via_web_services() {
-    userRule.createUser("root1", "bar");
-    userRule.createUser("root2", "bar");
-    WsClient root1WsClient = newUserWsClient(orchestrator, "root1", "bar");
-    WsClient root2WsClient = newUserWsClient(orchestrator, "root2", "bar");
+    WsUsers.CreateWsResponse.User user1 = tester.users().generate();
+    WsUsers.CreateWsResponse.User user2 = tester.users().generate();
+    Session user1Session = tester.as(user1.getLogin());
+    Session user2Session = tester.as(user2.getLogin());
 
     // non root can not set or unset root another user not itself
-    expectForbiddenError(() -> root1WsClient.rootService().setRoot("root2"));
-    expectForbiddenError(() -> root1WsClient.rootService().setRoot("root1"));
-    expectForbiddenError(() -> root1WsClient.rootService().unsetRoot("root1"));
-    expectForbiddenError(() -> root2WsClient.rootService().unsetRoot("root1"));
-    expectForbiddenError(() -> root2WsClient.rootService().unsetRoot("root2"));
+    expectForbiddenError(() -> user1Session.wsClient().roots().setRoot(user2.getLogin()));
+    expectForbiddenError(() -> user1Session.wsClient().roots().setRoot(user1.getLogin()));
+    expectForbiddenError(() -> user1Session.wsClient().roots().unsetRoot(user1.getLogin()));
+    expectForbiddenError(() -> user2Session.wsClient().roots().unsetRoot(user1.getLogin()));
+    expectForbiddenError(() -> user2Session.wsClient().roots().unsetRoot(user2.getLogin()));
     // admin (the first root) sets root1 as root
-    newAdminWsClient(orchestrator).rootService().setRoot("root1");
+    tester.wsClient().roots().setRoot(user1.getLogin());
     // root1 can set root root2
-    root1WsClient.rootService().setRoot("root2");
+    user1Session.wsClient().roots().setRoot(user2.getLogin());
     // root2 can unset root root1
-    root2WsClient.rootService().unsetRoot("root1");
+    user2Session.wsClient().roots().unsetRoot(user1.getLogin());
     // root2 can unset root itself as it's not the last root
-    root2WsClient.rootService().unsetRoot("root2");
+    user2Session.wsClient().roots().unsetRoot(user2.getLogin());
   }
 
 }
index 4e6c51eb1e3bd5965d1b0c8f83e5aab4f1772edf..c8bdc4c8b0b51e34d3e8977ed9cfcab39484eac4 100644 (file)
@@ -22,23 +22,26 @@ package it.organization;
 import com.sonar.orchestrator.Orchestrator;
 import it.Category4Suite;
 import org.junit.ClassRule;
+import org.junit.Rule;
 import org.junit.Test;
+import org.sonarqube.test.Tester;
 
 import static util.ItUtils.expectForbiddenError;
-import static util.ItUtils.newAdminWsClient;
-import static util.ItUtils.newWsClient;
 
 public class RootUserTest {
 
   @ClassRule
   public static Orchestrator orchestrator = Category4Suite.ORCHESTRATOR;
 
+  @Rule
+  public Tester tester = new Tester(orchestrator).disableOrganizations();
+
   @Test
   public void nobody_is_root_by_default_when_organizations_are_disabled() {
     // anonymous
-    expectForbiddenError(() -> newWsClient(orchestrator).rootService().search());
+    expectForbiddenError(() -> tester.wsClient().roots().search());
 
     // admin
-    expectForbiddenError(() -> newAdminWsClient(orchestrator).rootService().search());
+    expectForbiddenError(() -> tester.wsClient().roots().search());
   }
 }
index 4d5d8d0f41c84cae1102353a8d89fdc4d4883fa6..33651550e75d4fb3afa89eac7444f68e5273d1bd 100644 (file)
@@ -47,8 +47,7 @@ public class BackgroundTasksTest {
   @Rule
   public UserRule userRule = UserRule.from(ORCHESTRATOR);
 
-  @Rule
-  public Navigation nav = Navigation.get(ORCHESTRATOR);
+  private Navigation nav = Navigation.create(ORCHESTRATOR);
 
   @BeforeClass
   public static void beforeClass() {
@@ -86,6 +85,7 @@ public class BackgroundTasksTest {
 
   @Test
   public void display_error_stacktrace() {
+    Navigation nav = Navigation.create(ORCHESTRATOR);
     executeBuild("test-project", "Test Project", "2010-01-01");
 
     nav.logIn().submitCredentials(ADMIN_USER_LOGIN);
index 16050604201e787a4304949bece52bcbb2645eef..716463c2fdefe52399b975b9cbe177040accff47 100644 (file)
@@ -63,8 +63,7 @@ public class ProjectAdministrationTest {
   @Rule
   public UserRule userRule = UserRule.from(orchestrator);
 
-  @Rule
-  public Navigation nav = Navigation.get(orchestrator);
+  private Navigation nav = Navigation.create(orchestrator);
 
   private static final String PROJECT_KEY = "sample";
   private static final String FILE_KEY = "sample:src/main/xoo/sample/Sample.xoo";
index dee28a8c81f5e0c593ee571ef6957bf6d0d9ca51..ec55c8fe7ae128e28018a3963689c413555d7837 100644 (file)
@@ -25,7 +25,6 @@ import it.Category1Suite;
 import org.junit.Before;
 import org.junit.BeforeClass;
 import org.junit.ClassRule;
-import org.junit.Rule;
 import org.junit.Test;
 import org.sonarqube.ws.client.PostRequest;
 import org.sonarqube.ws.client.WsClient;
@@ -44,9 +43,6 @@ public class ProjectKeyPageTest {
   @ClassRule
   public static Orchestrator ORCHESTRATOR = Category1Suite.ORCHESTRATOR;
 
-  @Rule
-  public Navigation nav = Navigation.get(ORCHESTRATOR);
-
   private static WsClient wsClient;
 
   @BeforeClass
@@ -59,6 +55,8 @@ public class ProjectKeyPageTest {
     ORCHESTRATOR.resetData();
   }
 
+  private Navigation nav = Navigation.create(ORCHESTRATOR);
+
   @Test
   public void change_key_when_no_modules() {
     createProject("sample");
index f12ede6e94e2166d4e9d21c9deeec9746abfecf2..e9a96bd5a9ada4535daf078abdb0291f9db1ad11 100644 (file)
@@ -49,8 +49,7 @@ public class ProjectLinksPageTest {
   @ClassRule
   public static Orchestrator ORCHESTRATOR = Category1Suite.ORCHESTRATOR;
 
-  @Rule
-  public Navigation nav = Navigation.get(ORCHESTRATOR);
+  private Navigation nav = Navigation.create(ORCHESTRATOR);
 
   @Rule
   public UserRule userRule = UserRule.from(ORCHESTRATOR);
index 157d1f6ce5db4e1bf0344a826819335b3ba635a4..e1b3c33cb52687f448cccfc3beba5bade566c4a9 100644 (file)
@@ -42,8 +42,7 @@ public class ProjectPermissionsTest {
   @Rule
   public UserRule userRule = UserRule.from(orchestrator);
 
-  @Rule
-  public Navigation nav = Navigation.get(orchestrator);
+  private Navigation nav = Navigation.create(orchestrator);
   private String adminUser;
 
   @BeforeClass
index 4279326d15d539f0b2ad88403832ea327ed9ba61..2484cd298b665ccab3cd241f4ac590926a066a25 100644 (file)
@@ -27,7 +27,6 @@ import org.junit.Before;
 import org.junit.BeforeClass;
 import org.junit.ClassRule;
 import org.junit.Ignore;
-import org.junit.Rule;
 import org.junit.Test;
 import org.sonar.wsclient.qualitygate.QualityGate;
 import org.sonar.wsclient.qualitygate.QualityGateClient;
@@ -44,8 +43,7 @@ public class ProjectQualityGatePageTest {
   @ClassRule
   public static Orchestrator ORCHESTRATOR = Category1Suite.ORCHESTRATOR;
 
-  @Rule
-  public Navigation nav = Navigation.get(ORCHESTRATOR);
+  private Navigation nav = Navigation.create(ORCHESTRATOR);
 
   private static WsClient wsClient;
 
index 59944ac9fe02f3bae2c066cec922ca5a008ce8d8..8128fb2dc7dd37b00d4b2c9ffe0d8c8636f04162 100644 (file)
@@ -42,8 +42,7 @@ public class ProjectActivityPageTest {
   @Rule
   public UserRule userRule = UserRule.from(ORCHESTRATOR);
 
-  @Rule
-  public Navigation nav = Navigation.get(ORCHESTRATOR);
+  private Navigation nav = Navigation.create(ORCHESTRATOR);
 
   @Before
   public void setUp() throws Exception {
index 779ccb4da2c58e9fac496f2eac71a14b3659d44f..0e79925063958906a0e53a923b3d35c951658af9 100644 (file)
@@ -31,10 +31,9 @@ import org.junit.BeforeClass;
 import org.junit.ClassRule;
 import org.junit.Rule;
 import org.junit.Test;
+import org.sonarqube.test.Tester;
 import org.sonarqube.ws.Organizations.Organization;
-import pageobjects.Navigation;
 import pageobjects.projects.ProjectsPage;
-import util.OrganizationRule;
 
 import static com.codeborne.selenide.WebDriverRunner.url;
 import static java.util.Arrays.asList;
@@ -51,9 +50,7 @@ public class LeakProjectsPageTest {
   public static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
 
   @Rule
-  public OrganizationRule organizationRule = new OrganizationRule(orchestrator);
-  @Rule
-  public Navigation nav = Navigation.get(orchestrator);
+  public Tester tester = new Tester(orchestrator);
 
   private Organization organization;
 
@@ -69,7 +66,7 @@ public class LeakProjectsPageTest {
 
   @Before
   public void setUp() {
-    organization = organizationRule.create();
+    organization = tester.organizations().generate();
     restoreProfile(orchestrator, SearchProjectsTest.class.getResource("/projectSearch/SearchProjectsTest/with-many-rules.xml"), organization.getKey());
   }
 
@@ -86,7 +83,7 @@ public class LeakProjectsPageTest {
     analyzeProject(projectKey1, "shared/xoo-sample", null);
 
     // Check the facets and project cards
-    ProjectsPage page = nav.openProjects(organization.getKey());
+    ProjectsPage page = tester.openBrowser().openProjects(organization.getKey());
     page.changePerspective("Leak");
     assertThat(url()).endsWith("/projects?view=leak");
     page.shouldHaveTotal(2);
index f33f5b14b6ae6a457723920087356bcc78080bed..6ce32eccae5913951daf79a5a88e5afe84bb842f 100644 (file)
@@ -22,55 +22,58 @@ package it.projectSearch;
 import com.sonar.orchestrator.Orchestrator;
 import com.sonar.orchestrator.build.SonarScanner;
 import it.Category1Suite;
+import org.junit.AfterClass;
 import org.junit.Before;
 import org.junit.BeforeClass;
 import org.junit.ClassRule;
-import org.junit.Rule;
 import org.junit.Test;
+import org.junit.rules.RuleChain;
+import org.sonarqube.test.Tester;
+import org.sonarqube.ws.WsUsers;
 import org.sonarqube.ws.client.PostRequest;
 import org.sonarqube.ws.client.WsClient;
+import org.sonarqube.ws.client.project.DeleteRequest;
 import pageobjects.Navigation;
 import pageobjects.projects.ProjectsPage;
-import util.user.UserRule;
 
 import static com.codeborne.selenide.Selenide.clearBrowserLocalStorage;
 import static com.codeborne.selenide.WebDriverRunner.url;
 import static org.assertj.core.api.Assertions.assertThat;
-import static util.ItUtils.newUserWsClient;
 import static util.ItUtils.projectDir;
 
 public class ProjectsPageTest {
 
   @ClassRule
-  public static Orchestrator ORCHESTRATOR = Category1Suite.ORCHESTRATOR;
-
-  @Rule
-  public UserRule userRule = UserRule.from(ORCHESTRATOR);
-
-  @Rule
-  public Navigation nav = Navigation.get(ORCHESTRATOR);
+  public static Orchestrator orchestrator = Category1Suite.ORCHESTRATOR;
 
   private static final String PROJECT_KEY = "key-foo";
-  private WsClient userAdminWsClient;
-  private String adminUser;
+  private static Tester tester = new Tester(orchestrator).disableOrganizations();
+
+  @ClassRule
+  public static RuleChain ruleChain = RuleChain.outerRule(orchestrator)
+    .around(tester);
 
   @BeforeClass
   public static void setUp() {
-    ORCHESTRATOR.resetData();
-    ORCHESTRATOR.executeBuild(SonarScanner.create(projectDir("shared/xoo-sample")).setProjectKey(PROJECT_KEY));
-    ORCHESTRATOR.executeBuild(SonarScanner.create(projectDir("duplications/file-duplications")).setProjectKey("key-bar"));
+    orchestrator.resetData();
+    orchestrator.executeBuild(SonarScanner.create(projectDir("shared/xoo-sample")).setProjectKey(PROJECT_KEY));
+    orchestrator.executeBuild(SonarScanner.create(projectDir("duplications/file-duplications")).setProjectKey("key-bar"));
+  }
+
+  @AfterClass
+  public static void tearDown() {
+    tester.wsClient().projects().delete(DeleteRequest.builder().setKey(PROJECT_KEY).build());
+    tester.wsClient().projects().delete(DeleteRequest.builder().setKey("key-bar").build());
   }
 
   @Before
   public void before() {
-    adminUser = userRule.createAdminUser();
-    userAdminWsClient = newUserWsClient(ORCHESTRATOR, adminUser, adminUser);
     clearBrowserLocalStorage();
   }
 
   @Test
   public void should_display_projects() {
-    ProjectsPage page = nav.openProjects();
+    ProjectsPage page = tester.openBrowser().openProjects();
     page.shouldHaveTotal(2);
     page.getProjectByKey(PROJECT_KEY)
       .shouldHaveMeasure("reliability_rating", "A")
@@ -83,7 +86,7 @@ public class ProjectsPageTest {
 
   @Test
   public void should_display_facets() {
-    ProjectsPage page = nav.openProjects();
+    ProjectsPage page = tester.openBrowser().openProjects();
     page.getFacetByProperty("duplications")
       .shouldHaveValue("1", "1")
       .shouldHaveValue("2", "1")
@@ -95,7 +98,7 @@ public class ProjectsPageTest {
 
   @Test
   public void should_filter_using_facet() {
-    ProjectsPage page = nav.openProjects();
+    ProjectsPage page = tester.openBrowser().openProjects();
     page.shouldHaveTotal(2);
     page.getFacetByProperty("duplications").selectValue("3");
     page.shouldHaveTotal(1);
@@ -104,22 +107,25 @@ public class ProjectsPageTest {
   @Test
   public void should_open_default_page() {
     // default page can be "All Projects" or "Favorite Projects" depending on your last choice
+    Navigation nav = tester.openBrowser();
     ProjectsPage page = nav.openProjects();
 
     // all projects for anonymous user with default sorting to analysis date
     page.shouldHaveTotal(2).shouldDisplayAllProjectsWidthSort("-analysis_date");
 
     // all projects by default for logged in user
-    page = nav.logIn().submitCredentials(adminUser).openProjects();
+    WsUsers.CreateWsResponse.User administrator = tester.users().generateAdministrator();
+    page = nav.logIn().submitCredentials(administrator.getLogin()).openProjects();
     page.shouldHaveTotal(2).shouldDisplayAllProjects();
 
     // favorite one project
-    userAdminWsClient.favorites().add(PROJECT_KEY);
+    WsClient administratorWsClient = tester.as(administrator.getLogin()).wsClient();
+    administratorWsClient.favorites().add(PROJECT_KEY);
     page = nav.openProjects();
     page.shouldHaveTotal(1).shouldDisplayFavoriteProjects();
 
     // un-favorite this project
-    userAdminWsClient.favorites().remove(PROJECT_KEY);
+    administratorWsClient.favorites().remove(PROJECT_KEY);
     page = nav.openProjects();
     page.shouldHaveTotal(2).shouldDisplayAllProjects();
 
@@ -136,7 +142,7 @@ public class ProjectsPageTest {
 
   @Test
   public void should_add_language_to_facet() {
-    ProjectsPage page = nav.openProjects();
+    ProjectsPage page = tester.openBrowser().openProjects();
     page.getFacetByProperty("languages")
       .selectOptionItem("xoo2")
       .shouldHaveValue("xoo2", "0");
@@ -145,12 +151,12 @@ public class ProjectsPageTest {
   @Test
   public void should_add_tag_to_facet() {
     // Add some tags to this project
-    userAdminWsClient.wsConnector().call(
+    tester.wsClient().wsConnector().call(
       new PostRequest("api/project_tags/set")
         .setParam("project", PROJECT_KEY)
         .setParam("tags", "aa,bb,cc,dd,ee,ff,gg,hh,ii,jj,zz"));
 
-    ProjectsPage page = nav.openProjects();
+    ProjectsPage page = tester.openBrowser().openProjects();
     page.getFacetByProperty("tags")
       .shouldHaveValue("aa", "1")
       .shouldHaveValue("ii", "1")
@@ -160,7 +166,10 @@ public class ProjectsPageTest {
 
   @Test
   public void should_switch_between_perspectives() {
-    ProjectsPage page = nav.logIn().submitCredentials(adminUser).openProjects();
+    WsUsers.CreateWsResponse.User administrator = tester.users().generateAdministrator();
+    ProjectsPage page = tester.openBrowser()
+      .logIn().submitCredentials(administrator.getLogin())
+      .openProjects();
     page.changePerspective("Risk");
     assertThat(url()).endsWith("/projects?view=visualizations&visualization=risk");
     page.changePerspective("Leak");
@@ -169,7 +178,7 @@ public class ProjectsPageTest {
 
   @Test
   public void should_sort_by_facet() {
-    ProjectsPage page = nav.openProjects();
+    ProjectsPage page = tester.openBrowser().openProjects();
     page.sortProjects("Duplications");
     page.getProjectByIdx(0).shouldHaveMeasure("duplicated_lines_density", "63.7%");
     page.invertSorting();
@@ -178,14 +187,14 @@ public class ProjectsPageTest {
 
   @Test
   public void should_search_for_project() {
-    ProjectsPage page = nav.openProjects();
+    ProjectsPage page = tester.openBrowser().openProjects();
     page.searchProject("s").shouldHaveTotal(2);
     page.searchProject("sam").shouldHaveTotal(1);
   }
 
   @Test
   public void should_search_for_project_and_keep_other_filters() {
-    ProjectsPage page = nav.openProjects();
+    ProjectsPage page = tester.openBrowser().openProjects();
     page.shouldHaveTotal(2);
     page.getFacetByProperty("duplications").selectValue("3");
     page.shouldHaveTotal(1);
index abfd79bf6deb5bb68e9cb7242c0ddcb6706c98d2..534e06881563cffd470c2deb8ecca0cf190ba65a 100644 (file)
@@ -30,20 +30,19 @@ import org.junit.Before;
 import org.junit.ClassRule;
 import org.junit.Rule;
 import org.junit.Test;
+import org.sonarqube.test.Tester;
 import org.sonarqube.ws.Common;
 import org.sonarqube.ws.Organizations.Organization;
 import org.sonarqube.ws.WsComponents.Component;
 import org.sonarqube.ws.WsComponents.SearchProjectsWsResponse;
 import org.sonarqube.ws.client.component.SearchProjectsRequest;
 import org.sonarqube.ws.client.project.CreateRequest;
-import util.OrganizationRule;
 
 import static java.util.Arrays.asList;
 import static java.util.Collections.singletonList;
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.groups.Tuple.tuple;
 import static util.ItUtils.concat;
-import static util.ItUtils.newAdminWsClient;
 import static util.ItUtils.newProjectKey;
 import static util.ItUtils.projectDir;
 import static util.ItUtils.restoreProfile;
@@ -59,13 +58,13 @@ public class SearchProjectsTest {
   public static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
 
   @Rule
-  public OrganizationRule organizations = new OrganizationRule(orchestrator);
+  public Tester tester = new Tester(orchestrator);
 
   private Organization organization;
 
   @Before
   public void setUp() {
-    organization = organizations.create();
+    organization = tester.organizations().generate();
     restoreProfile(orchestrator, SearchProjectsTest.class.getResource("/projectSearch/SearchProjectsTest/with-many-rules.xml"), organization.getKey());
   }
 
@@ -91,7 +90,7 @@ public class SearchProjectsTest {
   @Test
   public void provisioned_projects_should_be_included_to_results() throws Exception {
     String projectKey = newProjectKey();
-    newAdminWsClient(orchestrator).projects().create(CreateRequest.builder().setKey(projectKey).setName(projectKey).setOrganization(organization.getKey()).build());
+    tester.wsClient().projects().create(CreateRequest.builder().setKey(projectKey).setName(projectKey).setOrganization(organization.getKey()).build());
 
     SearchProjectsWsResponse response = searchProjects(SearchProjectsRequest.builder().setOrganization(organization.getKey()).build());
 
@@ -110,7 +109,7 @@ public class SearchProjectsTest {
     analyzeProject(projectKey2, "shared/xoo-sample");
     // This project is provisioned, so has no leak period
     String projectKey3 = newProjectKey();
-    newAdminWsClient(orchestrator).projects().create(CreateRequest.builder().setKey(projectKey3).setName(projectKey3).setOrganization(organization.getKey()).build());
+    tester.wsClient().projects().create(CreateRequest.builder().setKey(projectKey3).setName(projectKey3).setOrganization(organization.getKey()).build());
 
     SearchProjectsWsResponse response = searchProjects(
       SearchProjectsRequest.builder().setAdditionalFields(singletonList("leakPeriodDate")).setOrganization(organization.getKey()).build());
@@ -294,7 +293,7 @@ public class SearchProjectsTest {
   }
 
   private SearchProjectsWsResponse searchProjects(SearchProjectsRequest request) throws IOException {
-    return newAdminWsClient(orchestrator).components().searchProjects(request);
+    return tester.wsClient().components().searchProjects(request);
   }
 
   private void verifyFilterMatches(String projectKey, String filter) throws IOException {
index a5469d05fbf4308217455deeeff329d8720d7fc1..9d09e69aebf569ab3b5db328065facf013ea5d82 100644 (file)
@@ -87,7 +87,8 @@ public class QualityGateUiTest {
     qgClient.updateCondition(UpdateCondition.create(lowThresholds.id()).metricKey("lines").operator("GT").warningThreshold("5000").errorThreshold("5000"));
     scanSampleWithDate(secondAnalysisDate);
 
-    ProjectActivityPage page = Navigation.get(orchestrator).openProjectActivity("sample");
+    Navigation nav = Navigation.create(orchestrator);
+    ProjectActivityPage page = nav.openProjectActivity("sample");
     page
       .assertFirstAnalysisOfTheDayHasText(secondAnalysisDate, "Green (was Orange)")
       .assertFirstAnalysisOfTheDayHasText(firstAnalysisDate, "Orange");
index 07ce9131de12783251698a20cf874aeaab4a4248..fa9a4e8ccd054646700fa22f287931a63eb59f68 100644 (file)
@@ -23,24 +23,21 @@ import com.sonar.orchestrator.Orchestrator;
 import it.Category6Suite;
 import java.util.function.Predicate;
 import org.junit.ClassRule;
+import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.RuleChain;
-import org.junit.rules.TestRule;
+import org.sonarqube.test.Session;
+import org.sonarqube.test.Tester;
 import org.sonarqube.ws.Organizations.Organization;
 import org.sonarqube.ws.QualityProfiles;
 import org.sonarqube.ws.QualityProfiles.CreateWsResponse;
 import org.sonarqube.ws.QualityProfiles.SearchWsResponse;
 import org.sonarqube.ws.QualityProfiles.SearchWsResponse.QualityProfile;
-import org.sonarqube.ws.WsUsers;
+import org.sonarqube.ws.WsUsers.CreateWsResponse.User;
 import org.sonarqube.ws.client.qualityprofile.ChangeParentRequest;
 import org.sonarqube.ws.client.qualityprofile.CopyRequest;
-import org.sonarqube.ws.client.qualityprofile.DeleteRequest;
+import org.sonarqube.ws.client.qualityprofile.QualityProfilesService;
 import org.sonarqube.ws.client.qualityprofile.SearchWsRequest;
 import org.sonarqube.ws.client.qualityprofile.SetDefaultRequest;
-import util.OrganizationRule;
-import util.QualityProfileRule;
-import util.QualityProfileSupport;
-import util.user.UserRule;
 
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.tuple;
@@ -48,23 +45,17 @@ import static util.ItUtils.expectBadRequestError;
 
 public class BuiltInQualityProfilesTest {
   private static final String RULE_ONE_BUG_PER_LINE = "xoo:OneBugIssuePerLine";
-  public static final String A_PASSWORD = "aPassword";
-
-  private static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
-  private static OrganizationRule organizations = new OrganizationRule(orchestrator);
-  private static QualityProfileRule profiles = new QualityProfileRule(orchestrator);
-  private static UserRule users = new UserRule(orchestrator);
 
   @ClassRule
-  public static TestRule chain = RuleChain.outerRule(orchestrator)
-    .around(organizations)
-    .around(profiles)
-    .around(users);
+  public static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
+
+  @Rule
+  public Tester tester = new Tester(orchestrator);
 
   @Test
   public void built_in_profiles_are_available_in_new_organization() {
-    Organization org = organizations.create();
-    SearchWsResponse result = profiles.getWsService().search(new SearchWsRequest().setOrganizationKey(org.getKey()));
+    Organization org = tester.organizations().generate();
+    SearchWsResponse result = tester.qProfiles().service().search(new SearchWsRequest().setOrganizationKey(org.getKey()));
 
     assertThat(result.getProfilesList())
       .extracting(QualityProfile::getName, QualityProfile::getLanguage, QualityProfile::getIsBuiltIn, QualityProfile::getIsDefault)
@@ -76,7 +67,7 @@ public class BuiltInQualityProfilesTest {
 
   @Test
   public void built_in_profiles_are_available_in_default_organization() {
-    SearchWsResponse result = profiles.getWsService().search(new SearchWsRequest().setOrganizationKey("default-organization"));
+    SearchWsResponse result = tester.qProfiles().service().search(new SearchWsRequest().setOrganizationKey("default-organization"));
 
     assertThat(result.getProfilesList())
       .extracting(QualityProfile::getOrganization, QualityProfile::getName, QualityProfile::getLanguage, QualityProfile::getIsBuiltIn, QualityProfile::getIsDefault)
@@ -88,34 +79,34 @@ public class BuiltInQualityProfilesTest {
 
   @Test
   public void cannot_delete_built_in_profile_even_when_not_the_default_profile() {
-    Organization org = organizations.create();
+    Organization org = tester.organizations().generate();
     QualityProfile builtInProfile = getProfile(org, p -> p.getIsBuiltIn() && p.getIsDefault() && "Basic".equals(p.getName()) && "xoo".equals(p.getLanguage()));
 
-    CreateWsResponse.QualityProfile profileInOrg = profiles.createXooProfile(org);
-    profiles.getWsService().setDefault(new SetDefaultRequest(profileInOrg.getKey()));
+    CreateWsResponse.QualityProfile profileInOrg = tester.qProfiles().createXooProfile(org);
+    tester.qProfiles().service().setDefault(new SetDefaultRequest(profileInOrg.getKey()));
 
-    expectBadRequestError(() ->
-      profiles.getWsService().delete(new DeleteRequest(builtInProfile.getKey())));
+    expectBadRequestError(() -> tester.qProfiles().service().delete(builtInProfile.getKey()));
   }
 
   @Test
   public void built_in_profile_cannot_be_modified() {
-    Organization org = organizations.create();
+    Organization org = tester.organizations().generate();
     QualityProfile builtInProfile = getProfile(org, p -> p.getIsBuiltIn() && p.getIsDefault() && "Basic".equals(p.getName()) && "xoo".equals(p.getLanguage()));
 
-    expectBadRequestError(() -> profiles.activateRule(builtInProfile, RULE_ONE_BUG_PER_LINE));
-    expectBadRequestError(() -> profiles.deactivateRule(builtInProfile, RULE_ONE_BUG_PER_LINE));
-    expectBadRequestError(() -> profiles.delete(builtInProfile));
+    QualityProfilesService service = tester.qProfiles().service();
+    expectBadRequestError(() -> tester.qProfiles().activateRule(builtInProfile.getKey(), RULE_ONE_BUG_PER_LINE));
+    expectBadRequestError(() -> service.deactivateRule(builtInProfile.getKey(), RULE_ONE_BUG_PER_LINE));
+    expectBadRequestError(() -> service.delete(builtInProfile.getKey()));
   }
 
   @Test
   public void copy_built_in_profile_to_a_custom_profile() {
-    Organization org = organizations.create();
-    WsUsers.CreateWsResponse.User administrator = users.createAdministrator(org, A_PASSWORD);
+    Organization org = tester.organizations().generate();
+    User administrator = tester.users().generateAdministrator(org);
     QualityProfile builtInProfile = getProfile(org, p -> p.getIsBuiltIn() && "Basic".equals(p.getName()) && "xoo".equals(p.getLanguage()));
-    QualityProfileSupport adminProfiles = profiles.as(administrator.getLogin(), A_PASSWORD);
+    Session adminSession = tester.as(administrator.getLogin());
 
-    QualityProfiles.CopyWsResponse copyResponse = adminProfiles.getWsService().copy(new CopyRequest(builtInProfile.getKey(), "My copy"));
+    QualityProfiles.CopyWsResponse copyResponse = adminSession.qProfiles().service().copy(new CopyRequest(builtInProfile.getKey(), "My copy"));
 
     assertThat(copyResponse.getIsDefault()).isFalse();
     assertThat(copyResponse.getKey()).isNotEmpty().isNotEqualTo(builtInProfile.getKey());
@@ -127,18 +118,18 @@ public class BuiltInQualityProfilesTest {
     assertThat(copy.getIsBuiltIn()).isFalse();
     assertThat(copy.getIsDefault()).isFalse();
     assertThat(builtInProfile.getActiveRuleCount()).isGreaterThan(0);
-    adminProfiles.assertThatNumberOfActiveRulesEqualsTo(copy, (int)builtInProfile.getActiveRuleCount());
+    adminSession.qProfiles().assertThatNumberOfActiveRulesEqualsTo(copy.getKey(), (int) builtInProfile.getActiveRuleCount());
   }
 
   @Test
   public void can_inherit_and_disinherit_from_built_in_profile_to_a_custom_profile() {
-    Organization org = organizations.create();
-    WsUsers.CreateWsResponse.User administrator = users.createAdministrator(org, A_PASSWORD);
+    Organization org = tester.organizations().generate();
+    User administrator = tester.users().generateAdministrator(org);
     QualityProfile builtInProfile = getProfile(org, p -> p.getIsBuiltIn() && "Basic".equals(p.getName()) && "xoo".equals(p.getLanguage()));
-    QualityProfileSupport adminProfiles = profiles.as(administrator.getLogin(), A_PASSWORD);
+    Session adminSession = tester.as(administrator.getLogin());
 
-    QualityProfiles.CopyWsResponse copyResponse = adminProfiles.getWsService().copy(new CopyRequest(builtInProfile.getKey(), "My copy"));
-    adminProfiles.getWsService().changeParent(
+    QualityProfiles.CopyWsResponse copyResponse = adminSession.qProfiles().service().copy(new CopyRequest(builtInProfile.getKey(), "My copy"));
+    adminSession.qProfiles().service().changeParent(
       ChangeParentRequest.builder().setParentKey(builtInProfile.getKey()).setProfileKey(copyResponse.getKey()).build());
 
     QualityProfile inheritedQualityPropfile = getProfile(org, p -> p.getKey().equals(copyResponse.getKey()));
@@ -147,7 +138,7 @@ public class BuiltInQualityProfilesTest {
     assertThat(inheritedQualityPropfile.getParentName()).isEqualTo(builtInProfile.getName());
 
     // Remove inheritance
-    adminProfiles.getWsService().changeParent(
+    adminSession.qProfiles().service().changeParent(
       new ChangeParentRequest(ChangeParentRequest.builder().setProfileKey(inheritedQualityPropfile.getKey())));
 
     inheritedQualityPropfile = getProfile(org, p -> p.getKey().equals(copyResponse.getKey()));
@@ -157,7 +148,7 @@ public class BuiltInQualityProfilesTest {
   }
 
   private QualityProfile getProfile(Organization organization, Predicate<QualityProfile> filter) {
-    return profiles.getWsService().search(new SearchWsRequest()
+    return tester.qProfiles().service().search(new SearchWsRequest()
       .setOrganizationKey(organization.getKey())).getProfilesList()
       .stream()
       .filter(filter)
index adf96f5fa1cf5735f4545e5fe92e9ccbb188f223..ab9cd6b658243ca5abc4e67e3d41620749b5c839 100644 (file)
@@ -21,19 +21,22 @@ package it.qualityProfile;
 
 import com.sonar.orchestrator.Orchestrator;
 import com.sonar.orchestrator.build.SonarScanner;
-import com.sonar.orchestrator.http.HttpMethod;
 import it.Category6Suite;
 import java.util.List;
 import java.util.Map;
 import java.util.function.Predicate;
 import org.junit.ClassRule;
+import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.RuleChain;
-import org.junit.rules.TestRule;
+import org.sonarqube.test.QProfileTester;
+import org.sonarqube.test.Session;
+import org.sonarqube.test.Tester;
 import org.sonarqube.ws.Organizations.Organization;
 import org.sonarqube.ws.QualityProfiles;
 import org.sonarqube.ws.QualityProfiles.CreateWsResponse.QualityProfile;
 import org.sonarqube.ws.WsUsers.CreateWsResponse.User;
+import org.sonarqube.ws.client.GetRequest;
+import org.sonarqube.ws.client.PostRequest;
 import org.sonarqube.ws.client.qualityprofile.AddProjectRequest;
 import org.sonarqube.ws.client.qualityprofile.ChangeParentRequest;
 import org.sonarqube.ws.client.qualityprofile.CopyRequest;
@@ -41,12 +44,8 @@ import org.sonarqube.ws.client.qualityprofile.CreateRequest;
 import org.sonarqube.ws.client.qualityprofile.SearchWsRequest;
 import org.sonarqube.ws.client.qualityprofile.SetDefaultRequest;
 import util.ItUtils;
-import util.OrganizationRule;
-import util.QualityProfileRule;
-import util.QualityProfileSupport;
-import util.user.UserRule;
 
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
 import static org.assertj.core.api.Assertions.assertThat;
 import static util.ItUtils.expectForbiddenError;
 import static util.ItUtils.expectMissingError;
@@ -55,116 +54,110 @@ import static util.ItUtils.projectDir;
 
 public class CustomQualityProfilesTest {
 
-  private static final String A_PASSWORD = "a_password";
-
-  private static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
-  private static OrganizationRule organizations = new OrganizationRule(orchestrator);
-  private static QualityProfileRule profiles = new QualityProfileRule(orchestrator);
-  private static UserRule users = new UserRule(orchestrator);
-
   @ClassRule
-  public static TestRule chain = RuleChain.outerRule(orchestrator)
-    .around(organizations)
-    .around(profiles)
-    .around(users);
+  public static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
+
+  @Rule
+  public Tester tester = new Tester(orchestrator);
 
   @Test
   public void activation_of_rules_is_isolated_among_organizations() {
     // create two profiles with same names in two organizations
-    Organization org1 = organizations.create();
-    Organization org2 = organizations.create();
-    QualityProfile profileInOrg1 = profiles.createXooProfile(org1, p -> p.setProfileName("foo"));
-    QualityProfile profileInOrg2 = profiles.createXooProfile(org2, p -> p.setProfileName("foo"));
+    Organization org1 = tester.organizations().generate();
+    Organization org2 = tester.organizations().generate();
+    QualityProfile profileInOrg1 = tester.qProfiles().createXooProfile(org1, p -> p.setProfileName("foo"));
+    QualityProfile profileInOrg2 = tester.qProfiles().createXooProfile(org2, p -> p.setProfileName("foo"));
 
-    profiles
+    tester.qProfiles()
       .assertThatNumberOfActiveRulesEqualsTo(profileInOrg1, 0)
       .assertThatNumberOfActiveRulesEqualsTo(profileInOrg2, 0);
 
-    profiles
+    tester.qProfiles()
       .activateRule(profileInOrg1, "xoo:OneIssuePerLine")
       .assertThatNumberOfActiveRulesEqualsTo(profileInOrg1, 1)
       .assertThatNumberOfActiveRulesEqualsTo(profileInOrg2, 0);
 
-    profiles
+    tester.qProfiles()
       .activateRule(profileInOrg1, "xoo:OneIssuePerFile")
       .assertThatNumberOfActiveRulesEqualsTo(profileInOrg1, 2)
       .assertThatNumberOfActiveRulesEqualsTo(profileInOrg2, 0);
 
-    profiles
+    tester.qProfiles()
       .deactivateRule(profileInOrg1, "xoo:OneIssuePerFile")
       .assertThatNumberOfActiveRulesEqualsTo(profileInOrg1, 1)
       .assertThatNumberOfActiveRulesEqualsTo(profileInOrg2, 0);
 
-    profiles
+    tester.qProfiles()
       .activateRule(profileInOrg2, "xoo:OneIssuePerFile")
       .assertThatNumberOfActiveRulesEqualsTo(profileInOrg1, 1)
       .assertThatNumberOfActiveRulesEqualsTo(profileInOrg2, 1);
 
-    profiles
-      .delete(profileInOrg1)
+    delete(profileInOrg1);
+    tester.qProfiles()
       .assertThatNumberOfActiveRulesEqualsTo(profileInOrg1, 0)
       .assertThatNumberOfActiveRulesEqualsTo(profileInOrg2, 1);
   }
 
   @Test
   public void an_organization_administrator_can_manage_the_profiles_of_organization() {
-    Organization org = organizations.create();
-    User user = users.createAdministrator(org, A_PASSWORD);
+    Organization org = tester.organizations().generate();
+    User user = tester.users().generateAdministrator(org);
 
-    QualityProfileSupport adminProfiles = profiles.as(user.getLogin(), A_PASSWORD);
-    QualityProfile profile = adminProfiles.createXooProfile(org);
-    adminProfiles.assertThatNumberOfActiveRulesEqualsTo(profile, 0);
+    QProfileTester adminSession = tester.as(user.getLogin()).qProfiles();
+    QualityProfile profile = adminSession.createXooProfile(org);
+    adminSession.assertThatNumberOfActiveRulesEqualsTo(profile, 0);
 
-    adminProfiles
+    adminSession
       .activateRule(profile, "xoo:OneIssuePerFile")
       .assertThatNumberOfActiveRulesEqualsTo(profile, 1);
 
-    adminProfiles
-      .delete(profile)
-      .assertThatNumberOfActiveRulesEqualsTo(profile, 0);
+    adminSession.service().delete(profile.getKey());
+    adminSession.assertThatNumberOfActiveRulesEqualsTo(profile, 0);
   }
 
   @Test
   public void deleting_an_organization_delete_all_profiles_on_this_organization() {
-    Organization org = organizations.create();
-    User user = users.createAdministrator(org, A_PASSWORD);
+    Organization org = tester.organizations().generate();
+    User user = tester.users().generateAdministrator(org);
 
-    QualityProfileSupport adminProfiles = profiles.as(user.getLogin(), A_PASSWORD);
+    QProfileTester adminSession = tester.as(user.getLogin()).qProfiles();
     // Profile
-    QualityProfile parentProfile = adminProfiles.createXooProfile(org);
+    QualityProfile parentProfile = adminSession.createXooProfile(org);
 
     // Copied profile
     QualityProfiles.SearchWsResponse.QualityProfile builtInProfile = getProfile(org, p -> p.getIsBuiltIn() && "Basic".equals(p.getName()) && "xoo".equals(p.getLanguage()));
-    QualityProfiles.CopyWsResponse copyResponse = adminProfiles.getWsService().copy(new CopyRequest(builtInProfile.getKey(), "My copy"));
+    QualityProfiles.CopyWsResponse copyResponse = adminSession.service().copy(new CopyRequest(builtInProfile.getKey(), "My copy"));
 
     // Inherited profile from custom
-    QualityProfile inheritedProfile1 = adminProfiles.getWsService().create(
+    QualityProfile inheritedProfile1 = adminSession.service().create(
       CreateRequest.builder()
         .setLanguage(parentProfile.getLanguage())
         .setOrganizationKey(org.getKey())
         .setProfileName("inherited_profile")
-        .build()).getProfile();
+        .build())
+      .getProfile();
 
-    adminProfiles.getWsService().changeParent(
+    adminSession.service().changeParent(
       ChangeParentRequest.builder().setParentKey(parentProfile.getKey()).setProfileKey(inheritedProfile1.getKey()).build());
 
     // Inherited profile from builtIn
-    QualityProfile inheritedProfile2 = adminProfiles.getWsService().create(
+    QualityProfile inheritedProfile2 = adminSession.service().create(
       CreateRequest.builder()
         .setLanguage(parentProfile.getLanguage())
         .setOrganizationKey(org.getKey())
         .setProfileName("inherited_profile2")
-        .build()).getProfile();
+        .build())
+      .getProfile();
 
-    adminProfiles.getWsService().changeParent(
+    adminSession.service().changeParent(
       ChangeParentRequest.builder().setParentKey(builtInProfile.getKey()).setProfileKey(inheritedProfile2.getKey()).build());
 
-    organizations.delete(org);
+    tester.organizations().service().delete(org.getKey());
 
-    expectMissingError(() -> profiles.getWsService().search(new SearchWsRequest()
-      .setOrganizationKey(org.getKey())).getProfilesList());
+    expectMissingError(() -> tester.qProfiles().service().search(new SearchWsRequest()
+      .setOrganizationKey(org.getKey())));
 
-    profiles.getWsService().search(new SearchWsRequest()).getProfilesList().stream()
+    tester.qProfiles().service().search(new SearchWsRequest()).getProfilesList()
       .forEach(p -> {
         assertThat(p.getOrganization()).isNotEqualTo(org.getKey());
         assertThat(p.getKey()).isNotIn(parentProfile.getKey(), copyResponse.getKey(), inheritedProfile1.getKey(), inheritedProfile2.getKey());
@@ -173,64 +166,68 @@ public class CustomQualityProfilesTest {
 
   @Test
   public void an_organization_administrator_cannot_manage_the_profiles_of_other_organizations() {
-    Organization org1 = organizations.create();
-    Organization org2 = organizations.create();
-    QualityProfile profileInOrg2 = profiles.createXooProfile(org2);
-    User adminOfOrg1 = users.createAdministrator(org1, A_PASSWORD);
+    Organization org1 = tester.organizations().generate();
+    Organization org2 = tester.organizations().generate();
+    QualityProfile profileInOrg2 = tester.qProfiles().createXooProfile(org2);
+    User adminOfOrg1 = tester.users().generateAdministrator(org1);
 
-    QualityProfileSupport adminProfiles = profiles.as(adminOfOrg1.getLogin(), A_PASSWORD);
+    QProfileTester adminSession = tester.as(adminOfOrg1.getLogin()).qProfiles();
+
+    expectForbiddenError(() -> adminSession.createXooProfile(org2));
+    expectForbiddenError(() -> adminSession.service().delete(profileInOrg2.getKey()));
+    expectForbiddenError(() -> adminSession.activateRule(profileInOrg2, "xoo:OneIssuePerFile"));
+    expectForbiddenError(() -> adminSession.deactivateRule(profileInOrg2, "xoo:OneIssuePerFile"));
+  }
 
-    expectForbiddenError(() -> adminProfiles.createXooProfile(org2));
-    expectForbiddenError(() -> adminProfiles.delete(profileInOrg2));
-    expectForbiddenError(() -> adminProfiles.activateRule(profileInOrg2, "xoo:OneIssuePerFile"));
-    expectForbiddenError(() -> adminProfiles.deactivateRule(profileInOrg2, "xoo:OneIssuePerFile"));
+  private void delete(QualityProfile profile) {
+    tester.qProfiles().service().delete(profile.getKey());
   }
 
   @Test
   public void anonymous_cannot_manage_the_profiles_of_an_organization() {
-    Organization org = organizations.create();
-    QualityProfile profile = profiles.createXooProfile(org);
+    Organization org = tester.organizations().generate();
+    QualityProfile profile = tester.qProfiles().createXooProfile(org);
 
-    QualityProfileSupport anonymousProfiles = profiles.asAnonymous();
+    Session anonymousSession = tester.asAnonymous();
 
-    expectUnauthorizedError(() -> anonymousProfiles.createXooProfile(org));
-    expectUnauthorizedError(() -> anonymousProfiles.delete(profile));
-    expectUnauthorizedError(() -> anonymousProfiles.activateRule(profile, "xoo:OneIssuePerFile"));
-    expectUnauthorizedError(() -> anonymousProfiles.deactivateRule(profile, "xoo:OneIssuePerFile"));
+    expectUnauthorizedError(() -> anonymousSession.qProfiles().createXooProfile(org));
+    expectUnauthorizedError(() -> anonymousSession.qProfiles().service().delete(profile.getKey()));
+    expectUnauthorizedError(() -> anonymousSession.qProfiles().activateRule(profile, "xoo:OneIssuePerFile"));
+    expectUnauthorizedError(() -> anonymousSession.qProfiles().deactivateRule(profile, "xoo:OneIssuePerFile"));
   }
 
   @Test
   public void root_can_manage_the_profiles_of_any_organization() {
-    Organization org = organizations.create();
+    Organization org = tester.organizations().generate();
 
-    User orgAdmin = users.createAdministrator(org, A_PASSWORD);
-    QualityProfileSupport adminProfiles = profiles.as(orgAdmin.getLogin(), A_PASSWORD);
-    QualityProfile profile = adminProfiles.createXooProfile(org);
+    User orgAdmin = tester.users().generateAdministrator(org);
+    Session adminSession = tester.as(orgAdmin.getLogin());
+    QualityProfile profile = adminSession.qProfiles().createXooProfile(org);
 
     // root can activate rule and delete the profile
-    profiles
+    tester.qProfiles()
       .activateRule(profile, "xoo:OneIssuePerFile")
       .assertThatNumberOfActiveRulesEqualsTo(profile, 1);
-    profiles
-      .delete(profile)
-      .assertThatNumberOfActiveRulesEqualsTo(profile, 0);
+    tester.qProfiles().service().delete(profile.getKey());
+    tester.qProfiles().assertThatNumberOfActiveRulesEqualsTo(profile, 0);
   }
 
   @Test
   public void can_inherit_and_disinherit_and__from_another_custom_profile() {
-    Organization org = organizations.create();
-    User user = users.createAdministrator(org, A_PASSWORD);
+    Organization org = tester.organizations().generate();
+    User user = tester.users().generateAdministrator(org);
 
-    QualityProfileSupport adminProfiles = profiles.as(user.getLogin(), A_PASSWORD);
-    QualityProfile parentProfile = adminProfiles.createXooProfile(org);
-    QualityProfile inheritedProfile = adminProfiles.getWsService().create(
+    Session adminSession = tester.as(user.getLogin());
+    QualityProfile parentProfile = adminSession.qProfiles().createXooProfile(org);
+    QualityProfile inheritedProfile = adminSession.qProfiles().service().create(
       CreateRequest.builder()
         .setLanguage(parentProfile.getLanguage())
         .setOrganizationKey(org.getKey())
         .setProfileName("inherited_profile")
-        .build()).getProfile();
+        .build())
+      .getProfile();
 
-    adminProfiles.getWsService().changeParent(
+    adminSession.qProfiles().service().changeParent(
       ChangeParentRequest.builder().setParentKey(parentProfile.getKey()).setProfileKey(inheritedProfile.getKey()).build());
 
     QualityProfiles.SearchWsResponse.QualityProfile inheritedQualityPropfile = getProfile(org, p -> p.getKey().equals(inheritedProfile.getKey()));
@@ -239,7 +236,7 @@ public class CustomQualityProfilesTest {
     assertThat(inheritedQualityPropfile.getParentName()).isEqualTo(parentProfile.getName());
 
     // Remove inheritance
-    adminProfiles.getWsService().changeParent(
+    adminSession.qProfiles().service().changeParent(
       new ChangeParentRequest(ChangeParentRequest.builder().setProfileKey(inheritedQualityPropfile.getKey())));
 
     inheritedQualityPropfile = getProfile(org, p -> p.getKey().equals(inheritedProfile.getKey()));
@@ -250,84 +247,79 @@ public class CustomQualityProfilesTest {
 
   @Test
   public void analysis_must_use_default_profile() {
-    Organization org = organizations.create();
-    User user = users.createAdministrator(org, A_PASSWORD);
+    Organization org = tester.organizations().generate();
+    User admin = tester.users().generateAdministrator(org);
 
-    QualityProfileSupport adminProfiles = profiles.as(user.getLogin(), A_PASSWORD);
+    Session adminSession = tester.as(admin.getLogin());
 
     String projectKey = randomAlphanumeric(10);
     String projectName = randomAlphanumeric(10);
     orchestrator.executeBuild(
       SonarScanner.create(projectDir("shared/xoo-sample"),
-        "sonar.login", user.getLogin(),
-        "sonar.password", A_PASSWORD,
+        "sonar.login", admin.getLogin(),
+        "sonar.password", admin.getLogin(),
         "sonar.organization", org.getKey())
         .setProjectKey(projectKey)
-        .setProjectName(projectName)
-    );
+        .setProjectName(projectName));
 
-    QualityProfiles.SearchWsResponse.QualityProfile defaultProfile = getProfile(org, p -> "xoo".equals(p.getLanguage()) && p.getIsDefault());
+    QualityProfiles.SearchWsResponse.QualityProfile defaultProfile = getProfile(org, p -> "xoo".equals(p.getLanguage()) &&
+      p.getIsDefault());
     assertThatQualityProfileIsUsedFor(projectKey, defaultProfile.getKey());
 
-    QualityProfile newXooProfile = adminProfiles.createXooProfile(org);
-    profiles.getWsService().setDefault(new SetDefaultRequest(newXooProfile.getKey()));
+    QualityProfile newXooProfile = adminSession.qProfiles().createXooProfile(org);
+    adminSession.qProfiles().service().setDefault(new SetDefaultRequest(newXooProfile.getKey()));
 
     orchestrator.executeBuild(
       SonarScanner.create(projectDir("shared/xoo-sample"),
-        "sonar.login", user.getLogin(),
-        "sonar.password", A_PASSWORD,
+        "sonar.login", admin.getLogin(),
+        "sonar.password", admin.getLogin(),
         "sonar.organization", org.getKey())
         .setProjectKey(projectKey)
-        .setProjectName(projectName)
-    );
+        .setProjectName(projectName));
 
     assertThatQualityProfileIsUsedFor(projectKey, newXooProfile.getKey());
   }
 
   @Test
   public void analysis_must_use_associated_profile() {
-    Organization org = organizations.create();
-    User user = users.createAdministrator(org, A_PASSWORD);
+    Organization org = tester.organizations().generate();
+    User admin = tester.users().generateAdministrator(org);
     String projectKey = randomAlphanumeric(10);
     String projectName = randomAlphanumeric(10);
-    QualityProfileSupport adminProfiles = profiles.as(user.getLogin(), A_PASSWORD);
-    QualityProfile newXooProfile = adminProfiles.createXooProfile(org);
+    Session adminSession = tester.as(admin.getLogin());
+    QualityProfile newXooProfile = adminSession.qProfiles().createXooProfile(org);
 
-    orchestrator.getServer().newHttpCall("api/projects/create")
-      .setCredentials(user.getLogin(), A_PASSWORD)
+    adminSession.wsClient().wsConnector().call(new PostRequest("api/projects/create")
       .setParam("project", projectKey)
       .setParam("name", projectName)
-      .setParam("organization", org.getKey())
-      .setMethod(HttpMethod.POST)
-      .execute();
+      .setParam("organization", org.getKey()));
 
-    adminProfiles.getWsService().addProject(AddProjectRequest.builder()
+    adminSession.qProfiles().service().addProject(AddProjectRequest.builder()
       .setProfileKey(newXooProfile.getKey())
       .setProjectKey(projectKey)
       .build());
 
     orchestrator.executeBuild(
       SonarScanner.create(projectDir("shared/xoo-sample"),
-        "sonar.login", user.getLogin(),
-        "sonar.password", A_PASSWORD,
+        "sonar.login", admin.getLogin(),
+        "sonar.password", admin.getLogin(),
         "sonar.organization", org.getKey())
         .setProjectKey(projectKey)
-        .setProjectName(projectName)
-    );
+        .setProjectName(projectName));
 
     assertThatQualityProfileIsUsedFor(projectKey, newXooProfile.getKey());
   }
 
-  private static void assertThatQualityProfileIsUsedFor(String projectKey, String qualityProfileKey) {
-    Map components = ItUtils.jsonToMap(orchestrator.getServer().newHttpCall("api/navigation/component")
-      .setParam("componentKey", projectKey)
-      .execute().getBodyAsString());
+  private void assertThatQualityProfileIsUsedFor(String projectKey, String qualityProfileKey) {
+    GetRequest request = new GetRequest("api/navigation/component")
+      .setParam("componentKey", projectKey);
+    Map components = ItUtils.jsonToMap(tester.wsClient().wsConnector().call(request).content());
 
     assertThat(((Map) ((List) components.get("qualityProfiles")).get(0)).get("key")).isEqualTo(qualityProfileKey);
   }
 
   private QualityProfiles.SearchWsResponse.QualityProfile getProfile(Organization organization, Predicate<QualityProfiles.SearchWsResponse.QualityProfile> filter) {
-    return profiles.getWsService().search(new SearchWsRequest()
+    return tester.qProfiles().service().search(new SearchWsRequest()
       .setOrganizationKey(organization.getKey())).getProfilesList()
       .stream()
       .filter(filter)
index 6b0d23c1c54807af893b90e7ae54a3146b5bbce1..11d31a89a6523159bc8ceec0c30fee5f6f977cb2 100644 (file)
@@ -23,79 +23,60 @@ import com.codeborne.selenide.Condition;
 import com.sonar.orchestrator.Orchestrator;
 import com.sonar.orchestrator.build.SonarScanner;
 import it.Category6Suite;
-import org.junit.After;
 import org.junit.Before;
 import org.junit.ClassRule;
 import org.junit.Ignore;
 import org.junit.Rule;
 import org.junit.Test;
+import org.sonarqube.test.Tester;
 import org.sonarqube.ws.Organizations;
 import org.sonarqube.ws.client.PostRequest;
-import org.sonarqube.ws.client.WsClient;
+import org.sonarqube.ws.client.qualityprofile.AddProjectRequest;
+import org.sonarqube.ws.client.qualityprofile.ChangeParentRequest;
 import pageobjects.Navigation;
-import util.OrganizationRule;
-import util.user.UserRule;
 
 import static com.codeborne.selenide.Selenide.$;
-import static util.ItUtils.newAdminWsClient;
 import static util.ItUtils.projectDir;
-import static util.selenium.Selenese.runSelenese;
 
 public class OrganizationQualityProfilesUiTest {
 
-  private final static String ROOT_USER = "root-user";
-
-  private static WsClient adminWsClient;
-
   @ClassRule
   public static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
+
   @Rule
-  public OrganizationRule organizationRule = new OrganizationRule(orchestrator);
-  @Rule
-  public UserRule userRule = UserRule.from(orchestrator);
+  public Tester tester = new Tester(orchestrator);
 
-  private static Organizations.Organization organization;
+  private Organizations.Organization organization;
 
   @Before
   public void setUp() {
-    adminWsClient = newAdminWsClient(orchestrator);
-    organization = organizationRule.create(o -> o.setKey("test-org").setName("test-org"));
-    userRule.createRootUser(ROOT_USER, ROOT_USER);
-  }
-
-  @Before
-  public void createSampleProfile() {
+    // key and name are overridden for HTML Selenese tests
+    organization = tester.organizations().generate(o -> o.setKey("test-org").setName("test-org"));
+    tester.users().generateAdministrator(organization, u -> u.setLogin("admin2").setPassword("admin2"));
     createProfile("xoo", "sample");
     inheritProfile("xoo", "sample", "Basic");
     analyzeProject("shared/xoo-sample");
     addProfileToProject("xoo", "sample", "sample");
   }
 
-  @After
-  public void deleteSampleProfile() {
-    setDefault("xoo", "Basic");
-    deleteProfile("xoo", "sample");
-    deleteProfile("xoo", "new name");
-  }
-
   @Test
   public void testNoGlobalPage() {
-    Navigation nav = Navigation.get(orchestrator);
+    Navigation nav = tester.openBrowser();
     nav.open("/profiles");
     $(".page-wrapper-simple").should(Condition.visible);
   }
 
   @Test
-  public void testHomePage() throws Exception {
-    runSelenese(orchestrator,
+  public void testHomePage() {
+    tester.runHtmlTests(
       "/organization/OrganizationQualityProfilesUiTest/should_display_list.html",
       "/organization/OrganizationQualityProfilesUiTest/should_open_from_list.html",
       "/organization/OrganizationQualityProfilesUiTest/should_filter_by_language.html");
   }
 
   @Test
-  public void testProfilePage() throws Exception {
-    runSelenese(orchestrator,
+  public void testProfilePage() {
+    tester.runHtmlTests(
       "/organization/OrganizationQualityProfilesUiTest/should_display_profile_rules.html",
       "/organization/OrganizationQualityProfilesUiTest/should_display_profile_inheritance.html",
       "/organization/OrganizationQualityProfilesUiTest/should_display_profile_projects.html",
@@ -104,7 +85,7 @@ public class OrganizationQualityProfilesUiTest {
 
   @Test
   public void testNotFound() {
-    Navigation nav = Navigation.get(orchestrator);
+    Navigation nav = tester.openBrowser();
     nav.open("/organizations/" + organization.getKey() + "/quality_profiles/show?key=unknown");
     $(".quality-profile-not-found").should(Condition.visible);
 
@@ -113,96 +94,88 @@ public class OrganizationQualityProfilesUiTest {
   }
 
   @Test
-  public void testProfileChangelog() throws Exception {
-    runSelenese(orchestrator,
+  public void testProfileChangelog() {
+    tester.runHtmlTests(
       "/organization/OrganizationQualityProfilesUiTest/should_display_changelog.html");
   }
 
-  @Ignore("find a way to know profile key inside selenium tests")
+  @Ignore("to be replaced by selenide test in order to inject profile key")
   @Test
-  public void testComparison() throws Exception {
-    runSelenese(orchestrator, "/organization/OrganizationQualityProfilesUiTest/should_compare.html");
+  public void testComparison() {
+    tester.runHtmlTests("/organization/OrganizationQualityProfilesUiTest/should_compare.html");
   }
 
   @Test
-  public void testCreation() throws Exception {
-    runSelenese(orchestrator, "/organization/OrganizationQualityProfilesUiTest/should_create.html");
+  public void testCreation() {
+    tester.runHtmlTests("/organization/OrganizationQualityProfilesUiTest/should_create.html");
   }
 
   @Test
-  public void testDeletion() throws Exception {
-    runSelenese(orchestrator, "/organization/OrganizationQualityProfilesUiTest/should_delete.html");
+  public void testDeletion() {
+    tester.runHtmlTests("/organization/OrganizationQualityProfilesUiTest/should_delete.html");
   }
 
   @Test
-  public void testCopying() throws Exception {
-    runSelenese(orchestrator, "/organization/OrganizationQualityProfilesUiTest/should_copy.html");
+  public void testCopying() {
+    tester.runHtmlTests("/organization/OrganizationQualityProfilesUiTest/should_copy.html");
   }
 
   @Test
-  public void testRenaming() throws Exception {
-    runSelenese(orchestrator, "/organization/OrganizationQualityProfilesUiTest/should_rename.html");
+  public void testRenaming() {
+    tester.runHtmlTests("/organization/OrganizationQualityProfilesUiTest/should_rename.html");
   }
 
   @Test
-  public void testSettingDefault() throws Exception {
-    runSelenese(orchestrator, "/organization/OrganizationQualityProfilesUiTest/should_set_default.html");
+  public void testSettingDefault() {
+    tester.runHtmlTests("/organization/OrganizationQualityProfilesUiTest/should_set_default.html");
   }
 
   @Test
-  public void testRestoration() throws Exception {
+  public void testRestoration() {
     deleteProfile("xoo", "empty");
 
-    runSelenese(orchestrator, "/organization/OrganizationQualityProfilesUiTest/should_restore.html");
+    tester.runHtmlTests("/organization/OrganizationQualityProfilesUiTest/should_restore.html");
   }
 
-  private static void createProfile(String language, String name) {
-    adminWsClient.wsConnector().call(
+  private void createProfile(String language, String name) {
+    tester.wsClient().wsConnector().call(
       new PostRequest("api/qualityprofiles/create")
         .setParam("language", language)
         .setParam("name", name)
         .setParam("organization", organization.getKey()));
   }
 
-  private static void inheritProfile(String language, String name, String parentName) {
-    adminWsClient.wsConnector().call(
-      new PostRequest("api/qualityprofiles/change_parent")
-        .setParam("language", language)
-        .setParam("profileName", name)
-        .setParam("parentName", parentName)
-        .setParam("organization", organization.getKey()));
+  private void inheritProfile(String language, String name, String parentName) {
+    tester.wsClient().qualityProfiles().changeParent(ChangeParentRequest.builder()
+      .setLanguage(language)
+      .setProfileName(name)
+      .setParentName(parentName)
+      .setOrganization(organization.getKey())
+      .build());
   }
 
-  private static void analyzeProject(String path) {
+  private void analyzeProject(String path) {
     orchestrator.executeBuild(SonarScanner.create(projectDir(path)).setProperties(
       "sonar.organization", organization.getKey(),
       "sonar.login", "admin",
       "sonar.password", "admin"));
   }
 
-  private static void addProfileToProject(String language, String profileName, String projectKey) {
-    adminWsClient.wsConnector().call(
-      new PostRequest("api/qualityprofiles/add_project")
-        .setParam("language", language)
-        .setParam("profileName", profileName)
-        .setParam("organization", organization.getKey())
-        .setParam("projectKey", projectKey));
+  private void addProfileToProject(String language, String profileName, String projectKey) {
+    tester.wsClient().qualityProfiles().addProject(AddProjectRequest.builder()
+      .setLanguage(language)
+      .setProfileName(profileName)
+      .setProjectKey(projectKey)
+      .setOrganization(organization.getKey())
+      .build());
   }
 
-  private static void deleteProfile(String language, String name) {
-    adminWsClient.wsConnector().call(
+  private void deleteProfile(String language, String name) {
+    tester.wsClient().wsConnector().call(
       new PostRequest("api/qualityprofiles/delete")
         .setParam("language", language)
         .setParam("profileName", name)
         .setParam("organization", organization.getKey()));
   }
 
-  private static void setDefault(String language, String name) {
-    adminWsClient.wsConnector().call(
-      new PostRequest("api/qualityprofiles/set_default")
-        .setParam("language", language)
-        .setParam("profileName", name)
-        .setParam("organization", organization.getKey()));
-  }
-
 }
index a4b1486618636450c685a7f308a74b19f431ac55..4aa69ae1978fa291a52d1105a9f9a302901a0bce 100644 (file)
@@ -25,20 +25,21 @@ import com.sonar.orchestrator.build.SonarScanner;
 import it.Category4Suite;
 import org.junit.After;
 import org.junit.Before;
-import org.junit.BeforeClass;
 import org.junit.ClassRule;
 import org.junit.Ignore;
 import org.junit.Rule;
 import org.junit.Test;
+import org.sonarqube.test.Tester;
 import org.sonarqube.ws.client.PostRequest;
 import org.sonarqube.ws.client.WsClient;
+import org.sonarqube.ws.client.qualityprofile.AddProjectRequest;
+import org.sonarqube.ws.client.qualityprofile.ChangeParentRequest;
+import org.sonarqube.ws.client.qualityprofile.CreateRequest;
 import pageobjects.Navigation;
 import util.user.UserRule;
 
 import static com.codeborne.selenide.Selenide.$;
-import static util.ItUtils.newAdminWsClient;
 import static util.ItUtils.projectDir;
-import static util.selenium.Selenese.runSelenese;
 
 public class QualityProfilesUiTest {
 
@@ -52,11 +53,8 @@ public class QualityProfilesUiTest {
 
   private static WsClient adminWsClient;
 
-  @BeforeClass
-  public static void setUp() {
-    adminWsClient = newAdminWsClient(orchestrator);
-    orchestrator.resetData();
-  }
+  @Rule
+  public Tester tester = new Tester(orchestrator).disableOrganizations();
 
   @Before
   public void initAdminUser() throws Exception {
@@ -77,23 +75,23 @@ public class QualityProfilesUiTest {
   }
 
   @After
-  public void deleteSampleProfile() {
+  public void tearDown() {
     setDefault("xoo", "Basic");
     deleteProfile("xoo", "sample");
     deleteProfile("xoo", "new name");
   }
 
   @Test
-  public void testHomePage() throws Exception {
-    runSelenese(orchestrator,
+  public void testHomePage() {
+    tester.runHtmlTests(
       "/qualityProfile/QualityProfilesUiTest/should_display_list.html",
       "/qualityProfile/QualityProfilesUiTest/should_open_from_list.html",
       "/qualityProfile/QualityProfilesUiTest/should_filter_by_language.html");
   }
 
   @Test
-  public void testProfilePage() throws Exception {
-    runSelenese(orchestrator,
+  public void testProfilePage() {
+    tester.runHtmlTests(
       "/qualityProfile/QualityProfilesUiTest/should_display_profile_rules.html",
       "/qualityProfile/QualityProfilesUiTest/should_display_profile_inheritance.html",
       "/qualityProfile/QualityProfilesUiTest/should_display_profile_projects.html",
@@ -102,7 +100,7 @@ public class QualityProfilesUiTest {
 
   @Test
   public void testNotFound() {
-    Navigation nav = Navigation.get(orchestrator);
+    Navigation nav = tester.openBrowser();
 
     nav.open("/profiles/show?key=unknown");
     $(".quality-profile-not-found").should(Condition.visible);
@@ -112,85 +110,85 @@ public class QualityProfilesUiTest {
   }
 
   @Test
-  public void testProfileChangelog() throws Exception {
-    runSelenese(orchestrator,
+  public void testProfileChangelog() {
+    tester.runHtmlTests(
       "/qualityProfile/QualityProfilesUiTest/should_display_changelog.html");
   }
 
   @Ignore("find a way to know profile key inside selenium tests")
   @Test
-  public void testComparison() throws Exception {
-    runSelenese(orchestrator, "/qualityProfile/QualityProfilesUiTest/should_compare.html");
+  public void testComparison() {
+    tester.runHtmlTests("/qualityProfile/QualityProfilesUiTest/should_compare.html");
   }
 
   @Test
-  public void testCreation() throws Exception {
-    runSelenese(orchestrator, "/qualityProfile/QualityProfilesUiTest/should_create.html");
+  public void testCreation() {
+    tester.runHtmlTests("/qualityProfile/QualityProfilesUiTest/should_create.html");
   }
 
   @Test
-  public void testDeletion() throws Exception {
-    runSelenese(orchestrator, "/qualityProfile/QualityProfilesUiTest/should_delete.html");
+  public void testDeletion() {
+    tester.runHtmlTests("/qualityProfile/QualityProfilesUiTest/should_delete.html");
   }
 
   @Test
-  public void testCopying() throws Exception {
-    runSelenese(orchestrator, "/qualityProfile/QualityProfilesUiTest/should_copy.html");
+  public void testCopying() {
+    tester.runHtmlTests("/qualityProfile/QualityProfilesUiTest/should_copy.html");
   }
 
   @Test
-  public void testRenaming() throws Exception {
-    runSelenese(orchestrator, "/qualityProfile/QualityProfilesUiTest/should_rename.html");
+  public void testRenaming() {
+    tester.runHtmlTests("/qualityProfile/QualityProfilesUiTest/should_rename.html");
   }
 
   @Test
-  public void testSettingDefault() throws Exception {
-    runSelenese(orchestrator, "/qualityProfile/QualityProfilesUiTest/should_set_default.html");
+  public void testSettingDefault() {
+    tester.runHtmlTests("/qualityProfile/QualityProfilesUiTest/should_set_default.html");
   }
 
   @Test
-  public void testRestoration() throws Exception {
+  public void testRestore() {
     deleteProfile("xoo", "empty");
 
-    runSelenese(orchestrator, "/qualityProfile/QualityProfilesUiTest/should_restore.html");
+    tester.runHtmlTests("/qualityProfile/QualityProfilesUiTest/should_restore.html");
   }
 
-  private static void createProfile(String language, String name) {
-    adminWsClient.wsConnector().call(
-      new PostRequest("api/qualityprofiles/create")
-        .setParam("language", language)
-        .setParam("name", name));
+  private void createProfile(String language, String name) {
+    tester.wsClient().qualityProfiles().create(CreateRequest.builder()
+      .setLanguage(language)
+      .setProfileName(name)
+      .build());
   }
 
-  private static void inheritProfile(String language, String name, String parentName) {
-    adminWsClient.wsConnector().call(
-      new PostRequest("api/qualityprofiles/change_parent")
-        .setParam("language", language)
-        .setParam("profileName", name)
-        .setParam("parentName", parentName));
+  private void inheritProfile(String language, String name, String parentName) {
+    tester.wsClient().qualityProfiles().changeParent(ChangeParentRequest.builder()
+      .setLanguage(language)
+      .setProfileName(name)
+      .setParentName(parentName)
+      .build());
   }
 
   private static void analyzeProject(String path) {
     orchestrator.executeBuild(SonarScanner.create(projectDir(path)));
   }
 
-  private static void addProfileToProject(String language, String profileName, String projectKey) {
-    adminWsClient.wsConnector().call(
-      new PostRequest("api/qualityprofiles/add_project")
-        .setParam("language", language)
-        .setParam("profileName", profileName)
-        .setParam("projectKey", projectKey));
+  private void addProfileToProject(String language, String profileName, String projectKey) {
+    tester.wsClient().qualityProfiles().addProject(AddProjectRequest.builder()
+      .setLanguage(language)
+      .setProfileName(profileName)
+      .setProjectKey(projectKey)
+      .build());
   }
 
-  private static void deleteProfile(String language, String name) {
-    adminWsClient.wsConnector().call(
+  private void deleteProfile(String language, String name) {
+    tester.wsClient().wsConnector().call(
       new PostRequest("api/qualityprofiles/delete")
         .setParam("language", language)
         .setParam("profileName", name));
   }
 
-  private static void setDefault(String language, String name) {
-    adminWsClient.wsConnector().call(
+  private void setDefault(String language, String name) {
+    tester.wsClient().wsConnector().call(
       new PostRequest("api/qualityprofiles/set_default")
         .setParam("language", language)
         .setParam("profileName", name));
index 80ba81eab6921584ef178f945bc2506466cf2ba4..282678824595581294a16280791c89cc989539cd 100644 (file)
@@ -20,7 +20,6 @@
 package it.rule;
 
 import com.sonar.orchestrator.Orchestrator;
-import com.sonar.orchestrator.http.HttpMethod;
 import it.Category6Suite;
 import java.util.List;
 import org.junit.BeforeClass;
@@ -28,29 +27,29 @@ import org.junit.ClassRule;
 import org.junit.Test;
 import org.junit.rules.RuleChain;
 import org.junit.rules.TestRule;
+import org.sonarqube.test.Tester;
 import org.sonarqube.ws.Organizations;
+import org.sonarqube.ws.client.PostRequest;
 import util.ItUtils;
-import util.OrganizationRule;
 
 import static org.assertj.core.api.Assertions.assertThat;
-import static util.ItUtils.newWsClient;
 
 public class RuleTagsTest {
 
   private static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
-  private static OrganizationRule organizations = new OrganizationRule(orchestrator);
+  private static Tester tester = new Tester(orchestrator);
 
   @ClassRule
   public static TestRule chain = RuleChain.outerRule(orchestrator)
-    .around(organizations);
+    .around(tester);
 
   private static Organizations.Organization organization1;
   private static Organizations.Organization organization2;
 
   @BeforeClass
   public static void setUp() {
-    organization1 = organizations.create();
-    organization2 = organizations.create();
+    organization1 = tester.organizations().generate();
+    organization2 = tester.organizations().generate();
   }
 
   @Test
@@ -97,17 +96,15 @@ public class RuleTagsTest {
   }
 
   private List<String> showRuleTags(Organizations.Organization organization) {
-    return newWsClient(orchestrator).rules().show(organization.getKey(), "xoo:OneIssuePerFile")
+    return tester.wsClient().rules().show(organization.getKey(), "xoo:OneIssuePerFile")
       .getRule().getTags().getTagsList();
   }
 
   private void updateTag(String tag, Organizations.Organization organization) {
-    orchestrator.getServer().newHttpCall("/api/rules/update")
-      .setMethod(HttpMethod.POST)
-      .setAdminCredentials()
+    tester.wsClient().wsConnector().call(new PostRequest("/api/rules/update")
       .setParam("organization", organization.getKey())
       .setParam("key", "xoo:OneIssuePerFile")
-      .setParam("tags", tag)
-      .execute();
+      .setParam("tags", tag))
+      .failIfNotSuccessful();
   }
 }
index 085302104d3e08e8f956516e4ea7b252058c8bbd..99b974df50d4104be9b7f20cf8e168c8f736e8af 100644 (file)
@@ -141,7 +141,7 @@ public class ClusterTest {
   }
 
   private static String getPropertyValue(Orchestrator web, String property) {
-    Settings.ValuesWsResponse response = ItUtils.newAdminWsClient(web).settingsService().values(ValuesRequest.builder().setKeys(property).build());
+    Settings.ValuesWsResponse response = ItUtils.newAdminWsClient(web).settings().values(ValuesRequest.builder().setKeys(property).build());
     List<Settings.Setting> settingsList = response.getSettingsList();
     if (settingsList.isEmpty()) {
       return null;
index 4433a9a390878bfc1b619c4cdeade8781c5bd210..6edb93ad3096aea349d7780740648df69f2d2244 100644 (file)
@@ -90,7 +90,7 @@ public class ServerSystemTest {
 
   @Test
   public void generate_server_id() throws IOException {
-    Navigation nav = Navigation.get(orchestrator).openHomepage().logIn().submitCredentials(ADMIN_USER_LOGIN);
+    Navigation nav = Navigation.create(orchestrator).openHome().logIn().submitCredentials(ADMIN_USER_LOGIN);
     String validIpAddress = getValidIpAddress();
 
     nav.openServerId()
index 01ce97261846efe6ca37d74e4a6e9a35f6c79b05..f98eef7565c459a215f7e16677409bce6a7a6c1c 100644 (file)
@@ -85,7 +85,7 @@ public class DeprecatedPropertiesWsTest {
     adminWsClient = newAdminWsClient(orchestrator);
     userWsClient = newUserWsClient(orchestrator, USER_LOGIN, "password");
     anonymousWsClient = newWsClient(orchestrator);
-    adminSettingsService = newAdminWsClient(orchestrator).settingsService();
+    adminSettingsService = newAdminWsClient(orchestrator).settings();
     runProjectAnalysis(orchestrator, "shared/xoo-multi-modules-sample");
   }
 
index 41a1cac6ce7d559f47b1cfff7cdccc9995a341b3..9d2924ed133916352b6136802b03165c00d73c45 100644 (file)
@@ -55,7 +55,7 @@ public class EmailsTest {
   @BeforeClass
   public static void before() throws Exception {
     ADMIN_WS_CLIENT = newAdminWsClient(orchestrator);
-    SETTINGS = ADMIN_WS_CLIENT.settingsService();
+    SETTINGS = ADMIN_WS_CLIENT.settings();
 
     SMTP_SERVER = new Wiser(0);
     SMTP_SERVER.start();
index f9779f3465eef8edb04661192acae81ac82c32a3..36c51a9c8bc88da50ca784d7b344a6a25f12cfc2 100644 (file)
@@ -45,8 +45,6 @@ public class LicensesPageTest {
   @Rule
   public UserRule userRule = UserRule.from(orchestrator);
 
-  @Rule
-  public Navigation nav = Navigation.get(orchestrator);
   private String adminUser;
 
   @BeforeClass
@@ -73,7 +71,7 @@ public class LicensesPageTest {
 
   @Test
   public void display_licenses() {
-    LicensesPage page = nav.logIn().submitCredentials(adminUser).openLicenses();
+    LicensesPage page = Navigation.create(orchestrator).logIn().submitCredentials(adminUser).openLicenses();
 
     page.getLicenses().shouldHaveSize(2);
     page.getLicensesAsItems().get(0).getName().shouldHave(text("Typed property"));
@@ -84,11 +82,11 @@ public class LicensesPageTest {
   public void change_licenses() {
     String EXAMPLE_LICENSE = "TmFtZTogRGV2ZWxvcHBlcnMKUGx1Z2luOiBhdXRvY29udHJvbApFeHBpcmVzOiAyMDEyLTA0LTAxCktleTogNjI5N2MxMzEwYzg2NDZiZTE5MDU1MWE4ZmZmYzk1OTBmYzEyYTIyMgo=";
 
-    LicensesPage page = nav.logIn().submitCredentials(adminUser).openLicenses();
+    LicensesPage page = Navigation.create(orchestrator).logIn().submitCredentials(adminUser).openLicenses();
     LicenseItem licenseItem = page.getLicenseByKey("typed.license.secured");
     licenseItem.setLicense(EXAMPLE_LICENSE);
 
-    ValuesWsResponse response = wsClient.settingsService()
+    ValuesWsResponse response = wsClient.settings()
       .values(ValuesRequest.builder().setKeys("typed.license.secured").build());
     assertThat(response.getSettings(0).getValue()).isEqualTo(EXAMPLE_LICENSE);
   }
index 2372f42073abadc0c8f253b43fedb2334eef6a97..d2be7424966f82b0e87f20b7eb757e7a6dbc0993 100644 (file)
@@ -53,15 +53,14 @@ public class PropertySetsTest {
   @Rule
   public UserRule userRule = UserRule.from(orchestrator);
 
-  @Rule
-  public Navigation nav = Navigation.get(orchestrator);
+  private Navigation nav = Navigation.create(orchestrator);
 
   static SettingsService SETTINGS;
   private String adminUser;
 
   @BeforeClass
   public static void initSettingsService() throws Exception {
-    SETTINGS = newAdminWsClient(orchestrator).settingsService();
+    SETTINGS = newAdminWsClient(orchestrator).settings();
   }
 
   @Before
index c53f507e2ba25eb8ed6eaf7195118d181dfb0d16..06c948ef8245a4a2ac37255aaa4a7853c54427f5 100644 (file)
@@ -80,17 +80,17 @@ public class SettingsTest {
     adminWsClient.permissions().removeGroup(new RemoveGroupWsRequest().setGroupName("anyone").setPermission("scan"));
 
     // Anonymous user, without 'Execute Analysis' permission
-    anonymousSettingsService = newWsClient(orchestrator).settingsService();
+    anonymousSettingsService = newWsClient(orchestrator).settings();
 
     // Authenticated user, without 'Execute Analysis' permission
-    userSettingsService = newUserWsClient(orchestrator, "setting-user", "setting-user").settingsService();
+    userSettingsService = newUserWsClient(orchestrator, "setting-user", "setting-user").settings();
 
     // User with 'Execute Analysis' permission
     adminWsClient.permissions().addUser(new AddUserWsRequest().setLogin("scanner-user").setPermission("scan"));
-    scanSettingsService = newUserWsClient(orchestrator, "scanner-user", "scanner-user").settingsService();
+    scanSettingsService = newUserWsClient(orchestrator, "scanner-user", "scanner-user").settings();
 
     // User with 'Administer System' permission but without 'Execute Analysis' permission
-    adminSettingsService = adminWsClient.settingsService();
+    adminSettingsService = adminWsClient.settings();
   }
 
   @AfterClass
index a38ba2f3eac4c3e0bb1be4b37ad4549ab91c2715..aafdf91bac9628cd23aca799f626e3c15b61ca83 100644 (file)
@@ -68,7 +68,7 @@ public class SettingsTestRestartingOrchestrator {
     startOrchestrator();
 
     String adminUser = userRule.createAdminUser();
-    Navigation nav = Navigation.get(orchestrator).openHomepage().logIn().submitCredentials(adminUser);
+    Navigation nav = Navigation.create(orchestrator).openHome().logIn().submitCredentials(adminUser);
 
     nav.openSettings(null)
       .assertMenuContains("General")
@@ -101,7 +101,7 @@ public class SettingsTestRestartingOrchestrator {
     orchestrator.executeBuilds(withDeprecatedKey, withNewKey);
 
     String adminUser = userRule.createAdminUser();
-    Navigation.get(orchestrator).openHomepage().logIn().submitCredentials(adminUser).openSettings(null)
+    Navigation.create(orchestrator).openHome().logIn().submitCredentials(adminUser).openSettings(null)
       .assertMenuContains("General")
       .assertSettingDisplayed("sonar.newKey")
       .assertSettingNotDisplayed("sonar.deprecatedKey");
index 9da1ed518dbd301d792a0d233878dadfd9df9a0e..70f02288fff752594f22d1699ffa011c132e8f81 100644 (file)
@@ -24,7 +24,6 @@ import com.sonar.orchestrator.build.SonarScanner;
 import it.Category4Suite;
 import org.junit.BeforeClass;
 import org.junit.ClassRule;
-import org.junit.Rule;
 import org.junit.Test;
 import pageobjects.Navigation;
 
@@ -37,8 +36,7 @@ public class SourceViewerTest {
   @ClassRule
   public static final Orchestrator ORCHESTRATOR = Category4Suite.ORCHESTRATOR;
 
-  @Rule
-  public Navigation nav = Navigation.get(ORCHESTRATOR);
+  private Navigation nav = Navigation.create(ORCHESTRATOR);
 
   @BeforeClass
   public static void beforeClass() {
index 6321cee2e85c66b2e3c1231f3ea2cbd024e594c1..c345140c517b419c0cc214c620c3b9f1ee04a5f6 100644 (file)
@@ -26,7 +26,6 @@ import java.util.Map;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.ClassRule;
-import org.junit.Rule;
 import org.junit.Test;
 import org.sonarqube.ws.client.GetRequest;
 import org.sonarqube.ws.client.WsResponse;
@@ -48,8 +47,7 @@ public class UiTest {
   @ClassRule
   public static final Orchestrator ORCHESTRATOR = Category4Suite.ORCHESTRATOR;
 
-  @Rule
-  public Navigation nav = Navigation.get(ORCHESTRATOR);
+  private Navigation nav = Navigation.create(ORCHESTRATOR);
 
   @Before
   @After
index c7a93d195754040f7f155e5843039790dad31b9d..0dad2a29535d070c8f88f8bc60dfefba8523a7fa 100644 (file)
@@ -22,17 +22,13 @@ package it.uiExtension;
 import com.codeborne.selenide.Condition;
 import com.sonar.orchestrator.Orchestrator;
 import it.Category6Suite;
-import org.junit.Before;
 import org.junit.ClassRule;
 import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.RuleChain;
-import org.junit.rules.TestRule;
 import org.openqa.selenium.By;
+import org.sonarqube.test.Tester;
 import org.sonarqube.ws.Organizations.Organization;
-import pageobjects.Navigation;
-import util.OrganizationRule;
-import util.user.UserRule;
+import org.sonarqube.ws.WsUsers.CreateWsResponse.User;
 
 import static com.codeborne.selenide.Condition.text;
 import static com.codeborne.selenide.Selenide.$;
@@ -41,29 +37,16 @@ import static org.assertj.core.api.Assertions.assertThat;
 
 public class OrganizationUiExtensionsTest {
 
-  private static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
-  private static OrganizationRule organizations = new OrganizationRule(orchestrator);
-  private static UserRule userRule = UserRule.from(orchestrator);
-
   @ClassRule
-  public static TestRule chain = RuleChain.outerRule(orchestrator)
-    .around(organizations)
-    .around(userRule);
+  public static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
 
   @Rule
-  public Navigation nav = Navigation.get(orchestrator);
-
-  private String adminUser;
-
-  @Before
-  public void before() {
-    adminUser = userRule.createRootUser();
-  }
+  public Tester tester = new Tester(orchestrator);
 
   @Test
   public void organization_page() {
-    Organization organization = organizations.create();
-    nav.open("/organizations/" + organization.getKey() + "/projects");
+    Organization organization = tester.organizations().generate();
+    tester.openBrowser().open("/organizations/" + organization.getKey() + "/projects");
 
     $("#organization-navigation-more").click();
     $(By.linkText("Organization Page")).shouldBe(Condition.visible).click();
@@ -74,8 +57,11 @@ public class OrganizationUiExtensionsTest {
 
   @Test
   public void organization_admin_page() {
-    Organization organization = organizations.create();
-    nav.logIn().submitCredentials(adminUser).open("/organizations/" + organization.getKey() + "/projects");
+    Organization organization = tester.organizations().generate();
+    User administrator = tester.users().generateAdministrator(organization);
+    tester.openBrowser()
+      .logIn().submitCredentials(administrator.getLogin())
+      .open("/organizations/" + organization.getKey() + "/projects");
 
     $("#context-navigation a.navbar-admin-link").click();
     $(By.linkText("Organization Admin Page")).shouldBe(Condition.visible).click();
index 16905e08ef6a78e3bd40eb5e44e4ad20e9c217a6..bd85a9327256cd4bf6a0aa4f4b477f497c65b944 100644 (file)
 package it.uiExtension;
 
 import com.sonar.orchestrator.Orchestrator;
-import com.sonar.orchestrator.build.SonarScanner;
 import it.Category4Suite;
-import org.junit.Before;
-import org.junit.BeforeClass;
 import org.junit.ClassRule;
 import org.junit.Rule;
 import org.junit.Test;
 import org.openqa.selenium.By;
-import pageobjects.Navigation;
-import util.user.UserRule;
+import org.sonarqube.test.Tester;
+import org.sonarqube.ws.WsProjects;
+import org.sonarqube.ws.WsUsers.CreateWsResponse.User;
+import org.sonarqube.ws.client.project.CreateRequest;
+import util.ItUtils;
 
 import static com.codeborne.selenide.Condition.text;
 import static com.codeborne.selenide.Selenide.$;
 import static com.codeborne.selenide.WebDriverRunner.url;
 import static org.assertj.core.api.Assertions.assertThat;
-import static util.ItUtils.projectDir;
-import static util.selenium.Selenese.runSelenese;
 
 public class UiExtensionsTest {
 
@@ -44,31 +42,16 @@ public class UiExtensionsTest {
   public static Orchestrator orchestrator = Category4Suite.ORCHESTRATOR;
 
   @Rule
-  public UserRule userRule = UserRule.from(orchestrator);
-
-  @Rule
-  public Navigation nav = Navigation.get(orchestrator);
-  private String adminUser;
-
-  @BeforeClass
-  public static void setUp() throws Exception {
-    orchestrator.resetData();
-    orchestrator.executeBuild(SonarScanner.create(projectDir("shared/xoo-sample")));
-  }
-
-  @Before
-  public void before() {
-    adminUser = userRule.createAdminUser();
-  }
+  public Tester tester = new Tester(orchestrator).disableOrganizations();
 
   @Test
   public void test_static_files() {
-    runSelenese(orchestrator, "/uiExtension/UiExtensionsTest/static-files.html");
+    tester.runHtmlTests("/uiExtension/UiExtensionsTest/static-files.html");
   }
 
   @Test
-  public void global_page() {
-    nav.open("/about");
+  public void test_global_page() {
+    tester.openBrowser().open("/about");
 
     // on about page
     $("#global-navigation-more").click();
@@ -79,8 +62,11 @@ public class UiExtensionsTest {
   }
 
   @Test
-  public void global_admin_page() {
-    nav.logIn().submitCredentials(adminUser).open("/about");
+  public void test_global_administration_page() {
+    User administrator = tester.users().generateAdministrator();
+    tester.openBrowser()
+      .logIn().submitCredentials(administrator.getLogin())
+      .open("/about");
 
     $(".navbar-admin-link").click();
     $("#settings-navigation-configuration").click();
@@ -91,8 +77,10 @@ public class UiExtensionsTest {
   }
 
   @Test
-  public void project_page() {
-    nav.open("/dashboard?id=sample");
+  public void test_project_page() {
+    WsProjects.CreateWsResponse.Project project = createSampleProject();
+
+    tester.openBrowser().open("/dashboard?id=" + project.getKey());
 
     $("#component-navigation-more").click();
     $(By.linkText("Project Page")).click();
@@ -102,8 +90,13 @@ public class UiExtensionsTest {
   }
 
   @Test
-  public void project_admin_page() {
-    nav.logIn().submitCredentials(adminUser).open("/dashboard?id=sample");
+  public void test_project_administration_page() {
+    WsProjects.CreateWsResponse.Project project = createSampleProject();
+    User administrator = tester.users().generateAdministrator();
+
+    tester.openBrowser()
+      .logIn().submitCredentials(administrator.getLogin())
+      .open("/dashboard?id=" + project.getKey());
 
     $("#component-navigation-admin").click();
     $(By.linkText("Project Admin Page")).click();
@@ -111,4 +104,12 @@ public class UiExtensionsTest {
     assertThat(url()).contains("uiextensionsplugin/project_admin_page");
     $("body").shouldHave(text("uiextensionsplugin/project_admin_page"));
   }
+
+  private WsProjects.CreateWsResponse.Project createSampleProject() {
+    String projectKey = ItUtils.newProjectKey();
+    return tester.wsClient().projects().create(CreateRequest.builder()
+      .setKey(projectKey)
+      .setName("Name of " + projectKey)
+      .build()).getProject();
+  }
 }
index 69213444b2a398815ed748380d5cbf6433c0aac6..391b2d892e5d30239b06b7644c4c05b5066f37be 100644 (file)
@@ -110,7 +110,7 @@ public class BaseIdentityProviderTest {
     enablePlugin();
     setUserCreatedByAuthPlugin(USER_LOGIN, USER_PROVIDER_ID, USER_NAME, USER_EMAIL);
 
-    Navigation.get(ORCHESTRATOR).openLogin().useOAuth2().shouldBeLoggedIn();
+    Navigation.create(ORCHESTRATOR).openLogin().useOAuth2().shouldBeLoggedIn();
 
     userRule.verifyUserExists(USER_LOGIN, USER_NAME, USER_EMAIL);
   }
index a69dd90d679d05eecc54f3e05118bc6fc157b106..a67756b43f1b7252e071697f178091adb482e449 100644 (file)
@@ -21,82 +21,74 @@ package it.user;
 
 import com.sonar.orchestrator.Orchestrator;
 import it.Category4Suite;
-import org.junit.AfterClass;
+import org.junit.After;
 import org.junit.Before;
 import org.junit.ClassRule;
 import org.junit.Rule;
 import org.junit.Test;
+import org.sonarqube.test.Tester;
+import org.sonarqube.ws.WsUsers.CreateWsResponse.User;
 import org.sonarqube.ws.client.GetRequest;
 import org.sonarqube.ws.client.PostRequest;
 import org.sonarqube.ws.client.WsClient;
+import org.sonarqube.ws.client.WsConnector;
 import org.sonarqube.ws.client.WsRequest;
 import org.sonarqube.ws.client.WsResponse;
 import pageobjects.Navigation;
-import util.user.UserRule;
 
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.sonarqube.ws.client.WsRequest.Method.GET;
 import static org.sonarqube.ws.client.WsRequest.Method.POST;
-import static util.ItUtils.newAdminWsClient;
-import static util.ItUtils.newWsClient;
 import static util.ItUtils.resetSettings;
 import static util.ItUtils.setServerProperty;
 
 public class ForceAuthenticationTest {
 
-  private static final String LOGIN = "force-authentication-user";
-
   @ClassRule
   public static final Orchestrator orchestrator = Category4Suite.ORCHESTRATOR;
 
   @Rule
-  public UserRule userRule = UserRule.from(orchestrator);
-
-  @Rule
-  public Navigation nav = Navigation.get(orchestrator);
-
-  private static WsClient anonymousClient;
-  private static WsClient adminWsClient;
+  public Tester tester = new Tester(orchestrator).disableOrganizations();
+  private User user;
 
   @Before
-  public void setUp() throws Exception {
-    userRule.resetUsers();
-    userRule.createUser(LOGIN, LOGIN);
+  public void setUp() {
     setServerProperty(orchestrator, "sonar.forceAuthentication", "true");
-    anonymousClient = newWsClient(orchestrator);
-    adminWsClient = newAdminWsClient(orchestrator);
+    user = tester.users().generate();
   }
 
-  @AfterClass
-  public static void tearDown() throws Exception {
+  @After
+  public void tearDown() {
     resetSettings(orchestrator, null, "sonar.forceAuthentication");
   }
 
   @Test
-  public void batch_ws_does_not_require_authentication() throws Exception {
-    WsResponse batchIndex = anonymousClient.wsConnector().call(new GetRequest("/batch/index")).failIfNotSuccessful();
+  public void batch_ws_does_not_require_authentication() {
+    WsConnector anonymousConnector = tester.asAnonymous().wsClient().wsConnector();
+    WsResponse batchIndex = anonymousConnector.call(new GetRequest("/batch/index")).failIfNotSuccessful();
     String batchIndexContent = batchIndex.content();
 
     assertThat(batchIndexContent).isNotEmpty();
     String jar = batchIndexContent.split("\\|")[0];
 
-    assertThat(anonymousClient.wsConnector().call(
+    assertThat(anonymousConnector.call(
       new GetRequest("/batch/file").setParam("name", jar)).failIfNotSuccessful().contentStream()).isNotNull();
 
     // As sonar-runner is still using deprecated /batch/key, we have to also verify it
-    assertThat(anonymousClient.wsConnector().call(new GetRequest("/batch/" + jar)).failIfNotSuccessful().contentStream()).isNotNull();
+    assertThat(anonymousConnector.call(new GetRequest("/batch/" + jar)).failIfNotSuccessful().contentStream()).isNotNull();
   }
 
   @Test
-  public void authentication_ws_does_not_require_authentication() throws Exception {
-    assertThat(anonymousClient.wsConnector().call(new PostRequest("/api/authentication/login")
-      .setParam("login", LOGIN)
-      .setParam("password", LOGIN)).isSuccessful()).isTrue();
+  public void authentication_ws_does_not_require_authentication() {
+    WsConnector anonymousConnector = tester.asAnonymous().wsClient().wsConnector();
+    assertThat(anonymousConnector.call(new PostRequest("/api/authentication/login")
+      .setParam("login", user.getLogin())
+      .setParam("password", user.getLogin())).isSuccessful()).isTrue();
     verifyPathDoesNotRequiresAuthentication("/api/authentication/logout", POST);
   }
 
   @Test
-  public void check_ws_not_requiring_authentication() throws Exception {
+  public void check_ws_not_requiring_authentication() {
     verifyPathDoesNotRequiresAuthentication("/api/system/db_migration_status", GET);
     verifyPathDoesNotRequiresAuthentication("/api/system/status", GET);
     verifyPathDoesNotRequiresAuthentication("/api/system/migrate_db", POST);
@@ -105,35 +97,36 @@ public class ForceAuthenticationTest {
   }
 
   @Test
-  public void check_ws_requiring_authentication() throws Exception {
+  public void check_ws_requiring_authentication() {
     verifyPathRequiresAuthentication("/api/issues/search", GET);
     verifyPathRequiresAuthentication("/api/rules/search", GET);
   }
 
   @Test
   public void redirect_to_login_page() {
-    String userAdmin = userRule.createAdminUser();
-    Navigation page = nav.openHomepage();
-    page.shouldBeRedirectToLogin();
-    page.openLogin().submitCredentials(userAdmin, userAdmin).shouldBeLoggedIn();
-    page.logOut().shouldBeRedirectToLogin();
+    User administrator = tester.users().generateAdministrator();
+    Navigation page = tester.openBrowser().openHome();
+    page.shouldBeRedirectedToLogin();
+    page.openLogin().submitCredentials(administrator.getLogin()).shouldBeLoggedIn();
+    page.logOut().shouldBeRedirectedToLogin();
   }
 
   private void verifyPathRequiresAuthentication(String path, WsRequest.Method method) {
-    assertThat(call(anonymousClient, path, method).code()).isEqualTo(401);
-    WsResponse wsResponse = call(adminWsClient, path, method);
+    assertThat(call(tester.asAnonymous().wsClient(), path, method).code()).isEqualTo(401);
+    WsResponse wsResponse = call(tester.wsClient(), path, method);
     assertThat(wsResponse.isSuccessful()).as("code is %s on path %s", wsResponse.code(), path).isTrue();
   }
 
   private void verifyPathDoesNotRequiresAuthentication(String path, WsRequest.Method method) {
-    WsResponse wsResponse = call(anonymousClient, path, method);
+    WsResponse wsResponse = call(tester.asAnonymous().wsClient(), path, method);
     assertThat(wsResponse.isSuccessful()).as("code is %s on path %s", wsResponse.code(), path).isTrue();
-    wsResponse = call(adminWsClient, path, method);
+    wsResponse = call(tester.wsClient(), path, method);
     assertThat(wsResponse.isSuccessful()).as("code is %s on path %s", wsResponse.code(), path).isTrue();
   }
 
   private WsResponse call(WsClient client, String path, WsRequest.Method method) {
-    return method.equals(GET) ? client.wsConnector().call(new GetRequest(path)) : client.wsConnector().call(new PostRequest(path));
+    WsRequest request = method.equals(GET) ? new GetRequest(path) : new PostRequest(path);
+    return client.wsConnector().call(request);
   }
 
 }
index b3f31f9d0cb1ba0ddc221a1d11bebe91e7e76487..dc6d2b0298e4900fd935d49dc60aecc269011bf5 100644 (file)
@@ -29,9 +29,11 @@ import org.junit.ClassRule;
 import org.junit.Ignore;
 import org.junit.Rule;
 import org.junit.Test;
+import org.sonarqube.test.Tester;
 import org.sonarqube.ws.WsUserTokens;
 import org.sonarqube.ws.client.GetRequest;
 import org.sonarqube.ws.client.HttpConnector;
+import org.sonarqube.ws.client.PostRequest;
 import org.sonarqube.ws.client.WsClient;
 import org.sonarqube.ws.client.WsClientFactories;
 import org.sonarqube.ws.client.WsResponse;
@@ -42,11 +44,9 @@ import org.sonarqube.ws.client.usertoken.SearchWsRequest;
 import org.sonarqube.ws.client.usertoken.UserTokensService;
 import pageobjects.LoginPage;
 import pageobjects.Navigation;
-import util.user.UserRule;
 
 import static java.lang.String.format;
 import static org.assertj.core.api.Assertions.assertThat;
-import static util.ItUtils.newAdminWsClient;
 import static util.ItUtils.resetSettings;
 import static util.ItUtils.setServerProperty;
 import static util.selenium.Selenese.runSelenese;
@@ -58,43 +58,28 @@ public class LocalAuthenticationTest {
   private static final String LOGIN = "george.orwell";
 
   @ClassRule
-  public static Orchestrator ORCHESTRATOR = Category4Suite.ORCHESTRATOR;
+  public static Orchestrator orchestrator = Category4Suite.ORCHESTRATOR;
 
   @Rule
-  public UserRule userRule = UserRule.from(ORCHESTRATOR);
-
-  @Rule
-  public Navigation nav = Navigation.get(ORCHESTRATOR);
-
-  private static WsClient adminWsClient;
-
-  private static UserTokensService userTokensWsClient;
+  public Tester tester = new Tester(orchestrator).disableOrganizations();
 
   @Before
   public void setUp() {
-    adminWsClient = newAdminWsClient(ORCHESTRATOR);
-    userTokensWsClient = adminWsClient.userTokens();
-
-    userRule.deactivateUsers(LOGIN, "simple-user");
-    userRule.createUser(LOGIN, "123456");
+    tester.users().generate(u -> u.setLogin(LOGIN).setPassword("123456"));
     addUserPermission(LOGIN, "admin");
 
-    userRule.createUser("simple-user", "password");
-    userRule.createAdminUser(ADMIN_USER_LOGIN, ADMIN_USER_LOGIN);
-  }
-
-  @After
-  public void deleteAndRestoreData() {
-    userRule.resetUsers();
+    tester.users().generate(u -> u.setLogin("simple-user").setPassword("password"));
+    tester.users().generateAdministrator(u -> u.setLogin(ADMIN_USER_LOGIN).setPassword(ADMIN_USER_LOGIN));
   }
 
   @After
   public void resetProperties() throws Exception {
-    resetSettings(ORCHESTRATOR, null, "sonar.forceAuthentication");
+    resetSettings(orchestrator, null, "sonar.forceAuthentication");
   }
 
   @Test
   public void log_in_with_correct_credentials_then_log_out() {
+    Navigation nav = tester.openBrowser();
     nav.shouldNotBeLoggedIn();
     nav.logIn().submitCredentials(LOGIN, "123456").shouldBeLoggedIn();
     nav.logOut().shouldNotBeLoggedIn();
@@ -102,12 +87,13 @@ public class LocalAuthenticationTest {
 
   @Test
   public void log_in_with_wrong_credentials() {
+    Navigation nav = tester.openBrowser();
     LoginPage page = nav
       .logIn()
       .submitWrongCredentials(LOGIN, "wrong");
     page.getErrorMessage().shouldHave(Condition.text("Authentication failed"));
 
-    nav.openHomepage();
+    nav.openHome();
     nav.shouldNotBeLoggedIn();
   }
 
@@ -117,10 +103,10 @@ public class LocalAuthenticationTest {
     String login = format("login-%s", userId);
     String name = format("name-%s", userId);
     String password = "!ascii-only:-)@";
-    userRule.createUser(login, name, null, password);
+    tester.users().generate(u -> u.setLogin(login).setName(name).setPassword(password));
 
     // authenticate
-    WsClient wsClient = WsClientFactories.getDefault().newClient(HttpConnector.newBuilder().url(ORCHESTRATOR.getServer().getUrl()).credentials(login, password).build());
+    WsClient wsClient = tester.as(login, password).wsClient();
     WsResponse response = wsClient.wsConnector().call(new GetRequest("api/authentication/validate"));
     assertThat(response.content()).isEqualTo("{\"valid\":true}");
   }
@@ -128,21 +114,22 @@ public class LocalAuthenticationTest {
   @Test
   public void basic_authentication_based_on_token() {
     String tokenName = "Validate token based authentication";
-    WsUserTokens.GenerateWsResponse generateWsResponse = userTokensWsClient.generate(new GenerateWsRequest()
+    UserTokensService tokensService = tester.wsClient().userTokens();
+    WsUserTokens.GenerateWsResponse generateWsResponse = tokensService.generate(new GenerateWsRequest()
       .setLogin(LOGIN)
       .setName(tokenName));
     WsClient wsClient = WsClientFactories.getDefault().newClient(HttpConnector.newBuilder()
-      .url(ORCHESTRATOR.getServer().getUrl())
+      .url(orchestrator.getServer().getUrl())
       .token(generateWsResponse.getToken()).build());
 
     WsResponse response = wsClient.wsConnector().call(new GetRequest("api/authentication/validate"));
 
     assertThat(response.content()).isEqualTo("{\"valid\":true}");
 
-    WsUserTokens.SearchWsResponse searchResponse = userTokensWsClient.search(new SearchWsRequest().setLogin(LOGIN));
+    WsUserTokens.SearchWsResponse searchResponse = tokensService.search(new SearchWsRequest().setLogin(LOGIN));
     assertThat(searchResponse.getUserTokensCount()).isEqualTo(1);
-    userTokensWsClient.revoke(new RevokeWsRequest().setLogin(LOGIN).setName(tokenName));
-    searchResponse = userTokensWsClient.search(new SearchWsRequest().setLogin(LOGIN));
+    tokensService.revoke(new RevokeWsRequest().setLogin(LOGIN).setName(tokenName));
+    searchResponse = tokensService.search(new SearchWsRequest().setLogin(LOGIN));
     assertThat(searchResponse.getUserTokensCount()).isEqualTo(0);
   }
 
@@ -159,7 +146,7 @@ public class LocalAuthenticationTest {
     String password = "κόσμε";
 
     // create user with a UTF-8 password
-    userRule.createUser(login, password);
+    tester.users().generate(u -> u.setLogin(login).setPassword(password));
 
     // authenticate
     assertThat(checkAuthenticationWithAuthenticateWebService(login, password)).isFalse();
@@ -167,14 +154,14 @@ public class LocalAuthenticationTest {
 
   @Test
   public void allow_user_login_with_2_characters() throws Exception {
-    userRule.createUser("jo", "password");
+    tester.users().generate(u -> u.setLogin("jo").setPassword("password"));
 
     assertThat(checkAuthenticationWithAuthenticateWebService("jo", "password")).isTrue();
   }
 
   @Test
   public void authentication_through_ui() {
-    runSelenese(ORCHESTRATOR,
+    runSelenese(orchestrator,
       "/user/LocalAuthenticationTest/login_successful.html",
       "/user/LocalAuthenticationTest/login_wrong_password.html",
       "/user/LocalAuthenticationTest/should_not_be_unlogged_when_going_to_login_page.html",
@@ -185,9 +172,9 @@ public class LocalAuthenticationTest {
       // SONAR-2009
       "/user/LocalAuthenticationTest/redirect_to_original_url_after_indirect_login.html");
 
-    setServerProperty(ORCHESTRATOR, "sonar.forceAuthentication", "true");
+    setServerProperty(orchestrator, "sonar.forceAuthentication", "true");
 
-    runSelenese(ORCHESTRATOR,
+    runSelenese(orchestrator,
       // SONAR-3473
       "/user/LocalAuthenticationTest/force-authentication.html");
   }
@@ -199,7 +186,7 @@ public class LocalAuthenticationTest {
     assertThat(checkAuthenticationWithAuthenticateWebService("admin", "wrong")).isFalse();
     assertThat(checkAuthenticationWithAuthenticateWebService(null, null)).isTrue();
 
-    setServerProperty(ORCHESTRATOR, "sonar.forceAuthentication", "true");
+    setServerProperty(orchestrator, "sonar.forceAuthentication", "true");
 
     assertThat(checkAuthenticationWithAuthenticateWebService("admin", "admin")).isTrue();
     assertThat(checkAuthenticationWithAuthenticateWebService("wrong", "admin")).isFalse();
@@ -218,7 +205,7 @@ public class LocalAuthenticationTest {
     assertThat(checkAuthenticationWithAnyWS("admin", null).code()).isEqualTo(401);
     assertThat(checkAuthenticationWithAnyWS(null, null).code()).isEqualTo(200);
 
-    setServerProperty(ORCHESTRATOR, "sonar.forceAuthentication", "true");
+    setServerProperty(orchestrator, "sonar.forceAuthentication", "true");
 
     assertThat(checkAuthenticationWithAnyWS("admin", "admin").code()).isEqualTo(200);
     assertThat(checkAuthenticationWithAnyWS("wrong", "admin").code()).isEqualTo(401);
@@ -228,18 +215,18 @@ public class LocalAuthenticationTest {
   }
 
   private boolean checkAuthenticationWithAuthenticateWebService(String login, String password) {
-    String result = ORCHESTRATOR.getServer().wsClient(login, password).get("/api/authentication/validate");
+    String result = tester.as(login, password).wsClient().wsConnector().call(new PostRequest("/api/authentication/validate")).content();
     return result.contains("{\"valid\":true}");
   }
 
   private WsResponse checkAuthenticationWithAnyWS(String login, String password) {
-    WsClient wsClient = WsClientFactories.getDefault().newClient(HttpConnector.newBuilder().url(ORCHESTRATOR.getServer().getUrl()).credentials(login, password).build());
+    WsClient wsClient = WsClientFactories.getDefault().newClient(HttpConnector.newBuilder().url(orchestrator.getServer().getUrl()).credentials(login, password).build());
     // Call any WS
     return wsClient.wsConnector().call(new GetRequest("api/rules/search"));
   }
 
-  private static void addUserPermission(String login, String permission) {
-    adminWsClient.permissions().addUser(new AddUserWsRequest()
+  private void addUserPermission(String login, String permission) {
+    tester.wsClient().permissions().addUser(new AddUserWsRequest()
       .setLogin(login)
       .setPermission(permission));
   }
index 5b3ac57ffccca76ad5b05f904770e6cff763d414..6d8b810568626af62d6c0a9e071c1933e6f5febb 100644 (file)
@@ -22,21 +22,18 @@ package it.user;
 import com.sonar.orchestrator.Orchestrator;
 import com.sonar.orchestrator.build.SonarScanner;
 import it.Category4Suite;
-import org.junit.After;
 import org.junit.Before;
-import org.junit.BeforeClass;
 import org.junit.ClassRule;
 import org.junit.Rule;
 import org.junit.Test;
+import org.sonarqube.test.Tester;
+import org.sonarqube.ws.WsUsers.CreateWsResponse.User;
 import org.sonarqube.ws.client.PostRequest;
-import org.sonarqube.ws.client.WsClient;
 import pageobjects.Navigation;
-import util.user.UserRule;
 
 import static com.codeborne.selenide.Condition.text;
 import static com.codeborne.selenide.Condition.visible;
 import static com.codeborne.selenide.Selenide.$;
-import static util.ItUtils.newAdminWsClient;
 import static util.ItUtils.projectDir;
 import static util.selenium.Selenese.runSelenese;
 
@@ -44,33 +41,21 @@ public class MyAccountPageTest {
 
   @ClassRule
   public static Orchestrator orchestrator = Category4Suite.ORCHESTRATOR;
-  private static WsClient adminWsClient;
 
   @Rule
-  public UserRule userRule = UserRule.from(orchestrator);
+  public Tester tester = new Tester(orchestrator).disableOrganizations();
 
-  @Rule
-  public Navigation nav = Navigation.get(orchestrator);
-  private String adminUser;
-
-  @BeforeClass
-  public static void setUp() {
-    adminWsClient = newAdminWsClient(orchestrator);
-  }
+  private User administrator;
 
   @Before
   public void initUser() {
-    adminUser = userRule.createAdminUser();
+    administrator = tester.users().generateAdministrator();
     createUser("account-user", "User With Account", "user@example.com");
   }
 
-  @After
-  public void deleteTestUser() {
-    deactivateUser("account-user");
-  }
-
   @Test
   public void should_display_user_details() throws Exception {
+    Navigation nav = tester.openBrowser();
     nav.openLogin().submitCredentials("account-user", "password").shouldBeLoggedIn();
     nav.open("/account");
     $("#name").shouldHave(text("User With Account"));
@@ -83,6 +68,7 @@ public class MyAccountPageTest {
 
   @Test
   public void should_change_password() throws Exception {
+    Navigation nav = tester.openBrowser();
     nav.openLogin().submitCredentials("account-user", "password").shouldBeLoggedIn();
     nav.open("/account/security");
     $("#old_password").val("password");
@@ -107,7 +93,8 @@ public class MyAccountPageTest {
 
   @Test
   public void notifications() {
-    nav.logIn().submitCredentials(adminUser).openNotifications()
+    Navigation nav = tester.openBrowser();
+    nav.logIn().submitCredentials(administrator.getLogin()).openNotifications()
       .addGlobalNotification("ChangesOnMyIssue")
       .addGlobalNotification("NewIssues")
       .removeGlobalNotification("ChangesOnMyIssue");
@@ -117,8 +104,8 @@ public class MyAccountPageTest {
       .shouldNotHaveGlobalNotification("ChangesOnMyIssue");
   }
 
-  private static void createUser(String login, String name, String email) {
-    adminWsClient.wsConnector().call(
+  private void createUser(String login, String name, String email) {
+    tester.wsClient().wsConnector().call(
       new PostRequest("api/users/create")
         .setParam("login", login)
         .setParam("name", name)
@@ -126,12 +113,6 @@ public class MyAccountPageTest {
         .setParam("password", "password"));
   }
 
-  private static void deactivateUser(String login) {
-    adminWsClient.wsConnector().call(
-      new PostRequest("api/users/deactivate")
-        .setParam("login", login));
-  }
-
   private static void analyzeProject(String projectKey) {
     SonarScanner build = SonarScanner.create(projectDir("qualitygate/xoo-sample"))
       .setProjectKey(projectKey)
@@ -140,8 +121,8 @@ public class MyAccountPageTest {
     orchestrator.executeBuild(build);
   }
 
-  private static void grantAdminPermission(String login, String projectKey) {
-    adminWsClient.wsConnector().call(
+  private void grantAdminPermission(String login, String projectKey) {
+    tester.wsClient().wsConnector().call(
       new PostRequest("api/permissions/add_user")
         .setParam("login", login)
         .setParam("projectKey", projectKey)
index d202a6b8402aec4a4db0aa7950134f4b590bb779..91a58eefe5b1898151a1ffc8c134bb7dec8ec608 100644 (file)
@@ -28,20 +28,17 @@ import okhttp3.mockwebserver.MockWebServer;
 import org.apache.commons.io.FileUtils;
 import org.junit.After;
 import org.junit.Before;
-import org.junit.BeforeClass;
 import org.junit.ClassRule;
 import org.junit.Rule;
 import org.junit.Test;
+import org.sonarqube.test.Tester;
+import org.sonarqube.ws.WsUsers.SearchWsResponse.User;
 import org.sonarqube.ws.client.GetRequest;
-import org.sonarqube.ws.client.WsClient;
 import org.sonarqube.ws.client.WsResponse;
 import org.sonarqube.ws.client.user.CreateRequest;
 import pageobjects.Navigation;
-import util.user.UserRule;
-import util.user.Users;
 
 import static org.assertj.core.api.Assertions.assertThat;
-import static util.ItUtils.newAdminWsClient;
 import static util.ItUtils.resetSettings;
 import static util.ItUtils.setServerProperty;
 import static util.selenium.Selenese.runSelenese;
@@ -52,28 +49,20 @@ import static util.selenium.Selenese.runSelenese;
 public class OAuth2IdentityProviderTest {
 
   @ClassRule
-  public static Orchestrator ORCHESTRATOR = Category4Suite.ORCHESTRATOR;
+  public static Orchestrator orchestrator = Category4Suite.ORCHESTRATOR;
 
-  @Rule
-  public UserRule userRule = UserRule.from(ORCHESTRATOR);
-
-  static String FAKE_PROVIDER_KEY = "fake-oauth2-id-provider";
-
-  static String USER_LOGIN = "john";
-  static String USER_PROVIDER_ID = "fake-john";
-  static String USER_NAME = "John";
-  static String USER_EMAIL = "john@email.com";
+  private static String FAKE_PROVIDER_KEY = "fake-oauth2-id-provider";
 
-  static WsClient adminWsClient;
+  private static String USER_LOGIN = "john";
+  private static String USER_PROVIDER_ID = "fake-john";
+  private static String USER_NAME = "John";
+  private static String USER_EMAIL = "john@email.com";
 
-  MockWebServer fakeServerAuthProvider;
-  String fakeServerAuthProviderUrl;
+  @Rule
+  public Tester tester = new Tester(orchestrator).disableOrganizations();
 
-  @BeforeClass
-  public static void initData() {
-    ORCHESTRATOR.resetData();
-    adminWsClient = newAdminWsClient(ORCHESTRATOR);
-  }
+  private MockWebServer fakeServerAuthProvider;
+  private String fakeServerAuthProviderUrl;
 
   @Before
   public void setUp() throws Exception {
@@ -89,9 +78,8 @@ public class OAuth2IdentityProviderTest {
     fakeServerAuthProvider.shutdown();
   }
 
-  private void resetData(){
-    userRule.resetUsers();
-    resetSettings(ORCHESTRATOR, null,
+  private void resetData() {
+    resetSettings(orchestrator, null,
       "sonar.auth.fake-oauth2-id-provider.enabled",
       "sonar.auth.fake-oauth2-id-provider.url",
       "sonar.auth.fake-oauth2-id-provider.user",
@@ -100,13 +88,21 @@ public class OAuth2IdentityProviderTest {
   }
 
   @Test
-  public void create_new_user_when_authenticate() throws Exception {
+  public void create_user_when_authenticating_for_the_first_time() {
     simulateRedirectionToCallback();
     enablePlugin();
 
     authenticateWithFakeAuthProvider();
 
-    userRule.verifyUserExists(USER_LOGIN, USER_NAME, USER_EMAIL);
+    verifyUser(USER_LOGIN, USER_NAME, USER_EMAIL);
+  }
+
+  private void verifyUser(String login, String name, String email) {
+    User user = tester.users().getByLogin(login).orElseThrow(IllegalStateException::new);
+    assertThat(user.getLogin()).isEqualTo(login);
+    assertThat(user.getName()).isEqualTo(name);
+    assertThat(user.getEmail()).isEqualTo(email);
+    assertThat(user.getActive()).isTrue();
   }
 
   @Test
@@ -114,9 +110,10 @@ public class OAuth2IdentityProviderTest {
     simulateRedirectionToCallback();
     enablePlugin();
 
-    Navigation.get(ORCHESTRATOR).openLogin().useOAuth2().shouldBeLoggedIn();
+    Navigation nav = tester.openBrowser();
+    nav.openLogin().useOAuth2().shouldBeLoggedIn();
 
-    userRule.verifyUserExists(USER_LOGIN, USER_NAME, USER_EMAIL);
+    verifyUser(USER_LOGIN, USER_NAME, USER_EMAIL);
   }
 
   @Test
@@ -125,49 +122,50 @@ public class OAuth2IdentityProviderTest {
     enablePlugin();
 
     // As this property is null, the plugin will throw an exception
-    setServerProperty(ORCHESTRATOR, "sonar.auth.fake-oauth2-id-provider.user", null);
+    setServerProperty(orchestrator, "sonar.auth.fake-oauth2-id-provider.user", null);
 
-    runSelenese(ORCHESTRATOR,"/user/OAuth2IdentityProviderTest/display_unauthorized_page_when_authentication_failed.html");
+    runSelenese(orchestrator, "/user/OAuth2IdentityProviderTest/display_unauthorized_page_when_authentication_failed.html");
 
-    userRule.verifyUserDoesNotExist(USER_LOGIN);
+    assertThatUserDoesNotExist(USER_LOGIN);
   }
 
   @Test
   public void fail_to_authenticate_when_not_allowed_to_sign_up() throws Exception {
     simulateRedirectionToCallback();
     enablePlugin();
-    setServerProperty(ORCHESTRATOR, "sonar.auth.fake-oauth2-id-provider.allowsUsersToSignUp", "false");
+    setServerProperty(orchestrator, "sonar.auth.fake-oauth2-id-provider.allowsUsersToSignUp", "false");
 
-    runSelenese(ORCHESTRATOR, "/user/OAuth2IdentityProviderTest/fail_to_authenticate_when_not_allowed_to_sign_up.html");
+    runSelenese(orchestrator, "/user/OAuth2IdentityProviderTest/fail_to_authenticate_when_not_allowed_to_sign_up.html");
 
-    userRule.verifyUserDoesNotExist(USER_LOGIN);
+    assertThatUserDoesNotExist(USER_LOGIN);
   }
 
   @Test
   public void display_message_in_ui_but_not_in_log_when_unauthorized_exception_in_callback() throws Exception {
     simulateRedirectionToCallback();
     enablePlugin();
-    setServerProperty(ORCHESTRATOR, "sonar.auth.fake-oauth2-id-provider.throwUnauthorizedMessage", "true");
+    setServerProperty(orchestrator, "sonar.auth.fake-oauth2-id-provider.throwUnauthorizedMessage", "true");
 
-    runSelenese(ORCHESTRATOR,"/user/OAuth2IdentityProviderTest/display_message_in_ui_but_not_in_log_when_unauthorized_exception.html");
+    tester.runHtmlTests("/user/OAuth2IdentityProviderTest/display_message_in_ui_but_not_in_log_when_unauthorized_exception.html");
 
-    File logFile = ORCHESTRATOR.getServer().getWebLogs();
+    File logFile = orchestrator.getServer().getWebLogs();
     assertThat(FileUtils.readFileToString(logFile)).doesNotContain("A functional error has happened");
     assertThat(FileUtils.readFileToString(logFile)).doesNotContain("UnauthorizedException");
 
-    userRule.verifyUserDoesNotExist(USER_LOGIN);
+    assertThatUserDoesNotExist(USER_LOGIN);
   }
 
   @Test
   public void fail_when_email_already_exists() throws Exception {
     simulateRedirectionToCallback();
     enablePlugin();
-    userRule.createUser("another", "Another", USER_EMAIL, "another");
+    tester.users().generate(u -> u.setLogin("another").setName("Another").setEmail(USER_EMAIL).setPassword("another"));
 
-    runSelenese(ORCHESTRATOR,"/user/OAuth2IdentityProviderTest/fail_when_email_already_exists.html");
+    tester.runHtmlTests("/user/OAuth2IdentityProviderTest/fail_when_email_already_exists.html");
 
-    File logFile = ORCHESTRATOR.getServer().getWebLogs();
-    assertThat(FileUtils.readFileToString(logFile)).doesNotContain("You can't sign up because email 'john@email.com' is already used by an existing user. This means that you probably already registered with another account");
+    File logFile = orchestrator.getServer().getWebLogs();
+    assertThat(FileUtils.readFileToString(logFile))
+      .doesNotContain("You can't sign up because email 'john@email.com' is already used by an existing user. This means that you probably already registered with another account");
   }
 
   @Test
@@ -176,26 +174,28 @@ public class OAuth2IdentityProviderTest {
     enablePlugin();
 
     // Provision none local user in database
-    newAdminWsClient(ORCHESTRATOR).users().create(CreateRequest.builder()
+    tester.wsClient().users().create(CreateRequest.builder()
       .setLogin(USER_LOGIN)
       .setName(USER_NAME)
       .setEmail(USER_EMAIL)
       .setLocal(false)
       .build());
-    assertThat(userRule.getUserByLogin(USER_LOGIN).get())
-      .extracting(Users.User::isLocal, Users.User::getExternalIdentity, Users.User::getExternalProvider)
-      .containsOnly(false, USER_LOGIN, "sonarqube");
+    User user = tester.users().getByLogin(USER_LOGIN).get();
+    assertThat(user.getLocal()).isFalse();
+    assertThat(user.getExternalIdentity()).isEqualTo(USER_LOGIN);
+    assertThat(user.getExternalProvider()).isEqualTo("sonarqube");
 
     // Authenticate with external system -> It will update external provider info
     authenticateWithFakeAuthProvider();
 
-    assertThat(userRule.getUserByLogin(USER_LOGIN).get())
-      .extracting(Users.User::isLocal, Users.User::getExternalIdentity, Users.User::getExternalProvider)
-      .containsOnly(false, USER_PROVIDER_ID, FAKE_PROVIDER_KEY);
+    user = tester.users().getByLogin(USER_LOGIN).get();
+    assertThat(user.getLocal()).isFalse();
+    assertThat(user.getExternalIdentity()).isEqualTo(USER_PROVIDER_ID);
+    assertThat(user.getExternalProvider()).isEqualTo(FAKE_PROVIDER_KEY);
   }
 
   private void authenticateWithFakeAuthProvider() {
-    WsResponse response = adminWsClient.wsConnector().call(
+    WsResponse response = tester.wsClient().wsConnector().call(
       new GetRequest(("/sessions/init/" + FAKE_PROVIDER_KEY)));
     assertThat(response.code()).isEqualTo(200);
   }
@@ -203,14 +203,18 @@ public class OAuth2IdentityProviderTest {
   private void simulateRedirectionToCallback() {
     fakeServerAuthProvider.enqueue(new MockResponse()
       .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
-      .addHeader("Location: " + ORCHESTRATOR.getServer().getUrl() + "/oauth2/callback/" + FAKE_PROVIDER_KEY)
+      .addHeader("Location: " + orchestrator.getServer().getUrl() + "/oauth2/callback/" + FAKE_PROVIDER_KEY)
       .setBody("Redirect to SonarQube"));
   }
 
   private void enablePlugin() {
-    setServerProperty(ORCHESTRATOR, "sonar.auth.fake-oauth2-id-provider.enabled", "true");
-    setServerProperty(ORCHESTRATOR, "sonar.auth.fake-oauth2-id-provider.url", fakeServerAuthProviderUrl);
-    setServerProperty(ORCHESTRATOR, "sonar.auth.fake-oauth2-id-provider.user", USER_LOGIN + "," + USER_PROVIDER_ID + "," + USER_NAME + "," + USER_EMAIL);
+    setServerProperty(orchestrator, "sonar.auth.fake-oauth2-id-provider.enabled", "true");
+    setServerProperty(orchestrator, "sonar.auth.fake-oauth2-id-provider.url", fakeServerAuthProviderUrl);
+    setServerProperty(orchestrator, "sonar.auth.fake-oauth2-id-provider.user", USER_LOGIN + "," + USER_PROVIDER_ID + "," + USER_NAME + "," + USER_EMAIL);
+  }
+
+  private void assertThatUserDoesNotExist(String login) {
+    assertThat(tester.users().getByLogin(login)).isEmpty();
   }
 
 }
index 9bd8530d48f306f3fbc5685b069a456f0e250e6c..ecc26fbe05642979d794f3ee6ee7478a2e25cf51 100644 (file)
 package it.user;
 
 import com.sonar.orchestrator.Orchestrator;
-import it.Category4Suite;
-import java.util.Optional;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.ClassRule;
 import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.sonarqube.ws.client.HttpException;
-import org.sonarqube.ws.client.user.UsersService;
-import util.user.UserRule;
+import org.sonarqube.test.Tester;
+import org.sonarqube.ws.WsUsers.CreateWsResponse.User;
+import org.sonarqube.ws.client.WsClient;
+import util.ItUtils;
 
-import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
 import static org.assertj.core.api.Assertions.assertThat;
-import static util.ItUtils.newAdminWsClient;
-import static util.ItUtils.newUserWsClient;
 import static util.ItUtils.resetSettings;
 import static util.ItUtils.setServerProperty;
 
 public class OnboardingTest {
 
-  @ClassRule
-  public static final Orchestrator orchestrator = Category4Suite.ORCHESTRATOR;
-  @ClassRule
-  public static UserRule userRule = UserRule.from(orchestrator);
-  @Rule
-  public ExpectedException expectedException = ExpectedException.none();
-
   private static final String ONBOARDING_TUTORIAL_SHOW_TO_NEW_USERS = "sonar.onboardingTutorial.showToNewUsers";
 
-  private String userLogin;
+  @ClassRule
+  public static final Orchestrator orchestrator = Orchestrator.builderEnv()
+    .build();
+
+  @Rule
+  public Tester tester = new Tester(orchestrator)
+    .disableOrganizations()
+    .enableOnBoardingTutorials();
 
   @Before
-  public void setUp() throws Exception {
+  public void setUp() {
     resetSettings(orchestrator, null, ONBOARDING_TUTORIAL_SHOW_TO_NEW_USERS);
   }
 
   @After
-  public void reset() throws Exception {
-    Optional.ofNullable(userLogin).ifPresent(login -> userRule.deactivateUsers(userLogin));
+  public void reset() {
     resetSettings(orchestrator, null, ONBOARDING_TUTORIAL_SHOW_TO_NEW_USERS);
   }
 
   @Test
   public void by_default_new_user_does_not_see_onboarding_tutorial() {
-    createUser();
+    User user = tester.users().generate();
 
-    assertOnboardingTutorial(false);
+    verifyTutorial(user, false);
   }
 
   @Test
   public void new_user_see_onboarding_tutorial_when_show_onboarding_setting_is_enabled() {
     setShownOnboardingSetting(true);
-    createUser();
+    User user = tester.users().generate();
 
-    assertOnboardingTutorial(true);
+    verifyTutorial(user, true);
   }
 
   @Test
   public void new_user_does_not_see_onboarding_tutorial_when_show_onboarding_setting_is_disabled() {
     setShownOnboardingSetting(false);
-    createUser();
+    User user = tester.users().generate();
 
-    assertOnboardingTutorial(false);
+    verifyTutorial(user, false);
   }
 
   @Test
   public void new_user_does_not_see_onboarding_tutorial_when_show_onboarding_setting_is_enabled_after_user_creation() {
     setShownOnboardingSetting(false);
     // User is created when show onboading is disabled
-    createUser();
+    User user = tester.users().generate();
     setShownOnboardingSetting(true);
 
     // The user doesn't see the tutorial as he was created when the show onboading setting was disabled
-    assertOnboardingTutorial(false);
+    verifyTutorial(user, false);
   }
 
   @Test
   public void skip_onboarding_tutorial() {
     setShownOnboardingSetting(true);
-    createUser();
+    User user = tester.users().generate();
 
-    createUsersServiceForUser().skipOnboardingTutorial();
+    tester.as(user.getLogin()).wsClient().users().skipOnboardingTutorial();
 
-    assertOnboardingTutorial(false);
+    verifyTutorial(user, false);
   }
 
   @Test
   public void skip_onboarding_tutorial_when_show_onboarding_setting_is_disabled() {
     setShownOnboardingSetting(true);
-    createUser();
+    User user = tester.users().generate();
 
-    createUsersServiceForUser().skipOnboardingTutorial();
+    tester.as(user.getLogin()).wsClient().users().skipOnboardingTutorial();
 
-    assertOnboardingTutorial(false);
+    verifyTutorial(user, false);
   }
 
   @Test
@@ -122,55 +116,49 @@ public class OnboardingTest {
     setShownOnboardingSetting(true);
 
     // anonymous should not see the onboarding tutorial
-    assertOnboardingTutorial(false);
+    verifyTutorialForAnonymous(false);
 
     // anonymous should not be able to skip the tutorial
-    expectedException.expect(HttpException.class);
-    createUsersServiceForUser().skipOnboardingTutorial();
+    ItUtils.expectHttpError(401, () -> tester.asAnonymous().wsClient().users().skipOnboardingTutorial());
   }
 
   @Test
   public void admin_user_see_onboarding_tutorial() {
-    UsersService adminService = newAdminWsClient(orchestrator).users();
 
-    assertThat(adminService.current().getShowOnboardingTutorial()).isEqualTo(true);
+    assertThat(tester.wsClient().users().current().getShowOnboardingTutorial()).isEqualTo(true);
 
     // Onboarding setting has no effect as admin is created at startup
     setShownOnboardingSetting(false);
-    assertThat(adminService.current().getShowOnboardingTutorial()).isEqualTo(true);
+    assertThat(tester.wsClient().users().current().getShowOnboardingTutorial()).isEqualTo(true);
 
     setShownOnboardingSetting(true);
-    assertThat(adminService.current().getShowOnboardingTutorial()).isEqualTo(true);
+    assertThat(tester.wsClient().users().current().getShowOnboardingTutorial()).isEqualTo(true);
   }
 
   @Test
   public void reactivated_user_should_see_the_onboarding_tutorial() {
     setShownOnboardingSetting(true);
-    createUser();
-    createUsersServiceForUser().skipOnboardingTutorial();
-    assertOnboardingTutorial(false);
+    User user = tester.users().generate();
+    tester.as(user.getLogin()).wsClient().users().skipOnboardingTutorial();
+    verifyTutorial(user, false);
 
-    userRule.deactivateUsers(userLogin);
-    userRule.createUser(userLogin, userLogin);
+    tester.wsClient().users().deactivate(user.getLogin());
+    User reactivatedUser = tester.users().generate(u -> u.setLogin(user.getLogin()).setName(user.getName()).setPassword(user.getLogin()));
 
-    assertOnboardingTutorial(true);
+    verifyTutorial(reactivatedUser, true);
   }
 
-  private void createUser() {
-    userLogin = randomAlphabetic(10).toLowerCase();
-    userRule.createUser(userLogin, userLogin);
+  private static void setShownOnboardingSetting(boolean showTutorial) {
+    setServerProperty(orchestrator, ONBOARDING_TUTORIAL_SHOW_TO_NEW_USERS, String.valueOf(showTutorial));
   }
 
-  private static void setShownOnboardingSetting(boolean showOnboardingTutorial) {
-    setServerProperty(orchestrator, ONBOARDING_TUTORIAL_SHOW_TO_NEW_USERS, String.valueOf(showOnboardingTutorial));
+  private void verifyTutorial(User user, boolean expectedTutorial) {
+    WsClient wsClient = tester.as(user.getLogin()).wsClient();
+    assertThat(wsClient.users().current().getShowOnboardingTutorial()).isEqualTo(expectedTutorial);
   }
 
-  private void assertOnboardingTutorial(boolean expectedOnboardingTutorial) {
-    assertThat(createUsersServiceForUser().current().getShowOnboardingTutorial()).isEqualTo(expectedOnboardingTutorial);
+  private void verifyTutorialForAnonymous(boolean expectedTutorial) {
+    WsClient wsClient = tester.asAnonymous().wsClient();
+    assertThat(wsClient.users().current().getShowOnboardingTutorial()).isEqualTo(expectedTutorial);
   }
-
-  private UsersService createUsersServiceForUser() {
-    return newUserWsClient(orchestrator, userLogin, userLogin).users();
-  }
-
 }
index 95f3ce894b17e85c75a347c3c58d9910fd75f699..d59f56514778d91791c97dd7ead1c2fd16d4affd 100644 (file)
@@ -22,112 +22,85 @@ package it.user;
 import com.google.common.base.Joiner;
 import com.sonar.orchestrator.Orchestrator;
 import it.Category6Suite;
-import org.junit.AfterClass;
+import org.junit.After;
 import org.junit.Before;
-import org.junit.BeforeClass;
 import org.junit.ClassRule;
+import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.RuleChain;
-import org.junit.rules.TestRule;
+import org.sonarqube.test.Tester;
+import org.sonarqube.ws.WsUserGroups.Group;
+import org.sonarqube.ws.WsUsers.CreateWsResponse.User;
 import org.sonarqube.ws.client.GetRequest;
-import org.sonarqube.ws.client.WsClient;
-import util.OrganizationRule;
-import util.user.UserRule;
 
-import static util.ItUtils.newAdminWsClient;
 import static util.ItUtils.resetSettings;
 import static util.ItUtils.setServerProperty;
 
 public class OrganizationIdentityProviderTest {
 
-  private static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
-  private static OrganizationRule organizations = new OrganizationRule(orchestrator);
-  private static UserRule users = new UserRule(orchestrator);
-
   @ClassRule
-  public static TestRule chain = RuleChain.outerRule(orchestrator)
-    .around(users)
-    .around(organizations);
+  public static Orchestrator orchestrator = Category6Suite.ORCHESTRATOR;
 
-  private static String USER_LOGIN = "john";
-  private static String GROUP = "group";
-  private static WsClient adminWsClient;
+  @Rule
+  public Tester tester = new Tester(orchestrator);
 
-  @BeforeClass
-  public static void before() {
-    adminWsClient = newAdminWsClient(orchestrator);
-    setServerProperty(orchestrator, "sonar.auth.fake-base-id-provider.enabled", "true");
-  }
-
-  @AfterClass
-  public static void cleanUp() throws Exception {
-    purgeSettings();
-  }
 
   @Before
-  public void setUp() throws Exception {
-    users.deactivateUsers(USER_LOGIN);
-    users.removeGroups(GROUP);
-    purgeSettings();
+  public void setUp() {
+    // enable the fake authentication plugin
+    setServerProperty(orchestrator, "sonar.auth.fake-base-id-provider.enabled", "true");
   }
 
-  private static void purgeSettings() {
+  @After
+  public void tearDown() {
     resetSettings(orchestrator, null, "sonar.auth.fake-base-id-provider.enabled", "sonar.auth.fake-base-id-provider.user",
       "sonar.auth.fake-base-id-provider.throwUnauthorizedMessage", "sonar.auth.fake-base-id-provider.enabledGroupsSync", "sonar.auth.fake-base-id-provider.groups",
       "sonar.auth.fake-base-id-provider.allowsUsersToSignUp");
   }
 
   @Test
-  public void default_group_is_not_added_for_new_user_when_organizations_are_enabled() throws Exception {
-    enablePlugin();
-    users.createGroup(GROUP);
-    enableUserCreationByAuthPlugin();
-    setGroupsReturnedByAuthPlugin(GROUP);
+  public void default_group_is_not_added_for_new_user_when_organizations_are_enabled()  {
+    Group group = tester.groups().generate(null);
+    enableUserCreationByAuthPlugin("aLogin");
+    setGroupsReturnedByAuthPlugin(group.getName());
 
     authenticateWithFakeAuthProvider();
 
     // No default group membership
-    users.verifyUserGroupMembership(USER_LOGIN, GROUP);
+    tester.groups().assertThatUserIsOnlyMemberOf(null, "aLogin", group.getName());
   }
 
   @Test
-  public void default_group_is_not_sync_for_existing_user_when_organizations_are_enabled() throws Exception {
-    enablePlugin();
-    users.createGroup(GROUP);
-    users.createUser(USER_LOGIN, "password");
-    enableUserCreationByAuthPlugin();
-    setGroupsReturnedByAuthPlugin(GROUP);
+  public void default_group_is_not_sync_for_existing_user_when_organizations_are_enabled() {
+    Group group = tester.groups().generate(null);
+    User user = tester.users().generate();
+    enableUserCreationByAuthPlugin(user.getLogin());
+    setGroupsReturnedByAuthPlugin(group.getName());
 
     authenticateWithFakeAuthProvider();
 
     // No default group membership
-    users.verifyUserGroupMembership(USER_LOGIN, GROUP);
+    tester.groups().assertThatUserIsOnlyMemberOf(null, user.getLogin(), group.getName());
   }
 
   @Test
-  public void remove_default_group_when_organizations_are_enabled() throws Exception {
-    enablePlugin();
-    users.createGroup(GROUP);
-    users.createUser(USER_LOGIN, "password");
+  public void remove_default_group_when_organizations_are_enabled() {
+    Group group = tester.groups().generate(null);
+    User user = tester.users().generate();
     // Add user as member of default organization
-    adminWsClient.organizations().addMember("default-organization", USER_LOGIN);
-    users.verifyUserGroupMembership(USER_LOGIN, "Members");
-    enableUserCreationByAuthPlugin();
+    tester.wsClient().organizations().addMember("default-organization", user.getLogin());
+    tester.groups().assertThatUserIsMemberOf(null, user.getLogin(), "Members");
+    enableUserCreationByAuthPlugin(user.getLogin());
     // No group is returned by the plugin
     setGroupsReturnedByAuthPlugin();
 
     authenticateWithFakeAuthProvider();
 
     // No default group membership
-    users.verifyUserGroupMembership(USER_LOGIN);
-  }
-
-  private static void enablePlugin() {
-    setServerProperty(orchestrator, "sonar.auth.fake-base-id-provider.enabled", "true");
+    tester.groups().assertThatUserIsOnlyMemberOf(null, user.getLogin());
   }
 
-  private static void enableUserCreationByAuthPlugin() {
-    setServerProperty(orchestrator, "sonar.auth.fake-base-id-provider.user", USER_LOGIN + ",fake-john,John,john@email.com");
+  private static void enableUserCreationByAuthPlugin(String login) {
+    setServerProperty(orchestrator, "sonar.auth.fake-base-id-provider.user", login + ",fake-john,John,john@email.com");
   }
 
   private static void setGroupsReturnedByAuthPlugin(String... groups) {
@@ -137,8 +110,8 @@ public class OrganizationIdentityProviderTest {
     }
   }
 
-  private static void authenticateWithFakeAuthProvider() {
-    adminWsClient.wsConnector().call(
+  private void authenticateWithFakeAuthProvider() {
+    tester.wsClient().wsConnector().call(
       new GetRequest("/sessions/init/fake-base-id-provider"))
       .failIfNotSuccessful();
   }
index e76bf2312b7cd33b18aa29fa8a1f2ca6ee33d107..d1b5390bcf2b825f21e5c7c3e74c86379b57b263 100644 (file)
@@ -270,10 +270,10 @@ public class WebhooksTest {
   private void setProperty(@Nullable String componentKey, String key, @Nullable String value) {
     if (value == null) {
       ResetRequest req = ResetRequest.builder().setKeys(key).setComponent(componentKey).build();
-      adminWs.settingsService().reset(req);
+      adminWs.settings().reset(req);
     } else {
       SetRequest req = SetRequest.builder().setKey(key).setValue(value).setComponent(componentKey).build();
-      adminWs.settingsService().set(req);
+      adminWs.settings().set(req);
     }
   }
 
diff --git a/it/it-tests/src/test/java/org/sonarqube/test/GroupTester.java b/it/it-tests/src/test/java/org/sonarqube/test/GroupTester.java
new file mode 100644 (file)
index 0000000..5b2242e
--- /dev/null
@@ -0,0 +1,102 @@
+/*
+ * SonarQube
+ * Copyright (C) 2009-2017 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.sonarqube.test;
+
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import org.sonarqube.ws.Organizations;
+import org.sonarqube.ws.WsUserGroups;
+import org.sonarqube.ws.WsUsers;
+import org.sonarqube.ws.WsUsers.GroupsWsResponse.Group;
+import org.sonarqube.ws.client.user.GroupsRequest;
+import org.sonarqube.ws.client.usergroup.AddUserWsRequest;
+import org.sonarqube.ws.client.usergroup.CreateWsRequest;
+
+import static java.util.Arrays.stream;
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class GroupTester {
+
+  private static final AtomicInteger ID_GENERATOR = new AtomicInteger();
+
+  private final Session session;
+
+  GroupTester(Session session) {
+    this.session = session;
+  }
+
+  @SafeVarargs
+  public final WsUserGroups.Group generate(@Nullable Organizations.Organization organization, Consumer<CreateWsRequest.Builder>... populators) {
+    int id = ID_GENERATOR.getAndIncrement();
+    CreateWsRequest.Builder request = CreateWsRequest.builder()
+      .setName("Group" + id)
+      .setDescription("Description " + id)
+      .setOrganization(organization != null ? organization.getKey() : null);
+    stream(populators).forEach(p -> p.accept(request));
+    return session.wsClient().userGroups().create(request.build()).getGroup();
+  }
+
+  public List<Group> getGroupsOfUser(@Nullable Organizations.Organization organization, String userLogin) {
+    GroupsRequest request = GroupsRequest.builder()
+      .setOrganization(organization != null ? organization.getKey() : null)
+      .setLogin(userLogin)
+      .build();
+    WsUsers.GroupsWsResponse response = session.users().service().groups(request);
+    return response.getGroupsList();
+  }
+
+  public GroupTester addMemberToGroups(Organizations.Organization organization, String userLogin, String... groups) {
+    for (String group : groups) {
+      AddUserWsRequest request = AddUserWsRequest.builder()
+        .setLogin(userLogin)
+        .setOrganization(organization.getKey())
+        .setName(group)
+        .build();
+      session.wsClient().userGroups().addUser(request);
+    }
+    return this;
+  }
+
+  public GroupTester assertThatUserIsMemberOf(@Nullable Organizations.Organization organization, String userLogin, String expectedGroup, String... otherExpectedGroups) {
+    List<String> groups = getGroupsOfUser(organization, userLogin)
+      .stream()
+      .map(Group::getName)
+      .collect(Collectors.toList());
+
+    assertThat(groups).contains(expectedGroup);
+    if (otherExpectedGroups.length > 0) {
+      assertThat(groups).contains(otherExpectedGroups);
+    }
+    return this;
+  }
+
+  public GroupTester assertThatUserIsOnlyMemberOf(@Nullable Organizations.Organization organization, String userLogin, String... expectedGroups) {
+    Set<String> groups = getGroupsOfUser(organization, userLogin)
+      .stream()
+      .map(Group::getName)
+      .collect(Collectors.toSet());
+    assertThat(groups).containsExactlyInAnyOrder(expectedGroups);
+    return this;
+  }
+}
diff --git a/it/it-tests/src/test/java/org/sonarqube/test/OrganizationTester.java b/it/it-tests/src/test/java/org/sonarqube/test/OrganizationTester.java
new file mode 100644 (file)
index 0000000..8925813
--- /dev/null
@@ -0,0 +1,134 @@
+/*
+ * SonarQube
+ * Copyright (C) 2009-2017 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.sonarqube.test;
+
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
+import javax.annotation.Nullable;
+import org.sonarqube.ws.Organizations;
+import org.sonarqube.ws.WsUsers;
+import org.sonarqube.ws.client.HttpException;
+import org.sonarqube.ws.client.PostRequest;
+import org.sonarqube.ws.client.organization.CreateWsRequest;
+import org.sonarqube.ws.client.organization.OrganizationService;
+import org.sonarqube.ws.client.organization.SearchMembersWsRequest;
+import org.sonarqube.ws.client.organization.SearchWsRequest;
+import org.sonarqube.ws.client.user.GroupsRequest;
+
+import static java.util.Arrays.stream;
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class OrganizationTester {
+
+  private static final AtomicInteger ID_GENERATOR = new AtomicInteger();
+
+  private final Session session;
+
+  OrganizationTester(Session session) {
+    this.session = session;
+  }
+
+  void enableSupport() {
+    session.wsClient().wsConnector().call(new PostRequest("api/organizations/enable_support"));
+  }
+
+  void deleteNonGuardedOrganizations() {
+    service().search(SearchWsRequest.builder().build()).getOrganizationsList()
+      .stream()
+      .filter(o -> !o.getKey().equals("default-organization"))
+      .forEach(organization -> service().delete(organization.getKey()));
+  }
+
+  @SafeVarargs
+  public final Organizations.Organization generate(Consumer<CreateWsRequest.Builder>... populators) {
+    int id = ID_GENERATOR.getAndIncrement();
+    CreateWsRequest.Builder request = new CreateWsRequest.Builder()
+      .setKey("org" + id)
+      .setName("Org " + id)
+      .setDescription("Description " + id)
+      .setUrl("http://test" + id);
+    stream(populators).forEach(p -> p.accept(request));
+    return service().create(request.build()).getOrganization();
+  }
+
+  public OrganizationTester addMember(Organizations.Organization organization, WsUsers.CreateWsResponse.User user) {
+    service().addMember(organization.getKey(), user.getLogin());
+    return this;
+  }
+
+  public OrganizationTester assertThatOrganizationDoesNotExist(String organizationKey) {
+    SearchWsRequest request = new SearchWsRequest.Builder().setOrganizations(organizationKey).build();
+    Organizations.SearchWsResponse searchWsResponse = service().search(request);
+    assertThat(searchWsResponse.getOrganizationsList()).isEmpty();
+    return this;
+  }
+
+  public OrganizationTester assertThatMemberOf(Organizations.Organization organization, WsUsers.CreateWsResponse.User user) {
+    return assertThatMemberOf(organization, user.getLogin());
+  }
+
+  public OrganizationTester assertThatMemberOf(Organizations.Organization organization, String userLogin) {
+    verifyOrganizationMembership(organization, userLogin, true);
+    verifyMembersGroupMembership(userLogin, organization, true);
+    return this;
+  }
+
+  public OrganizationTester assertThatNotMemberOf(Organizations.Organization organization, WsUsers.CreateWsResponse.User user) {
+    return assertThatNotMemberOf(organization, user.getLogin());
+  }
+
+  public OrganizationTester assertThatNotMemberOf(Organizations.Organization organization, String userLogin) {
+    verifyOrganizationMembership(organization, userLogin, false);
+    try {
+      verifyMembersGroupMembership(userLogin, organization, false);
+    } catch (HttpException e) {
+      // do not fail if user does not exist
+      if (e.code() != 404) {
+        throw e;
+      }
+    }
+    return this;
+  }
+
+  private void verifyOrganizationMembership(@Nullable Organizations.Organization organization, String userLogin, boolean isMember) {
+    List<Organizations.User> users = service().searchMembers(new SearchMembersWsRequest()
+      .setQuery(userLogin)
+      .setSelected("selected")
+      .setOrganization(organization != null ? organization.getKey() : null))
+      .getUsersList();
+    assertThat(users).hasSize(isMember ? 1 : 0);
+  }
+
+  private void verifyMembersGroupMembership(String userLogin, @Nullable Organizations.Organization organization, boolean isMember) {
+    List<WsUsers.GroupsWsResponse.Group> groups = session.wsClient().users().groups(GroupsRequest.builder()
+      .setLogin(userLogin)
+      .setOrganization(organization != null ? organization.getKey() : null)
+      .setQuery("Members")
+      .setSelected("selected")
+      .build())
+      .getGroupsList();
+    assertThat(groups).hasSize(isMember ? 1 : 0);
+  }
+
+  public OrganizationService service() {
+    return session.wsClient().organizations();
+  }
+}
diff --git a/it/it-tests/src/test/java/org/sonarqube/test/QProfileTester.java b/it/it-tests/src/test/java/org/sonarqube/test/QProfileTester.java
new file mode 100644 (file)
index 0000000..fc14a92
--- /dev/null
@@ -0,0 +1,118 @@
+/*
+ * SonarQube
+ * Copyright (C) 2009-2017 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.sonarqube.test;
+
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
+import org.sonarqube.ws.Common;
+import org.sonarqube.ws.Organizations.Organization;
+import org.sonarqube.ws.QualityProfiles.CreateWsResponse.QualityProfile;
+import org.sonarqube.ws.Rules;
+import org.sonarqube.ws.client.HttpException;
+import org.sonarqube.ws.client.qualityprofile.ActivateRuleWsRequest;
+import org.sonarqube.ws.client.qualityprofile.CreateRequest;
+import org.sonarqube.ws.client.qualityprofile.QualityProfilesService;
+import org.sonarqube.ws.client.rule.SearchWsRequest;
+
+import static java.util.Arrays.asList;
+import static java.util.Arrays.stream;
+import static java.util.Collections.singletonList;
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class QProfileTester {
+  private static final AtomicInteger ID_GENERATOR = new AtomicInteger();
+
+  private final Session session;
+
+  QProfileTester(Session session) {
+    this.session = session;
+  }
+
+  public QualityProfilesService service() {
+    return session.wsClient().qualityProfiles();
+  }
+
+  @SafeVarargs
+  public final QualityProfile createXooProfile(Organization organization, Consumer<CreateRequest.Builder>... populators) {
+    int id = ID_GENERATOR.getAndIncrement();
+    CreateRequest.Builder request = CreateRequest.builder()
+      .setOrganizationKey(organization.getKey())
+      .setLanguage("xoo")
+      .setProfileName("Profile" + id);
+    stream(populators).forEach(p -> p.accept(request));
+    return service().create(request.build()).getProfile();
+  }
+
+  public QProfileTester activateRule(QualityProfile profile, String ruleKey) {
+    return activateRule(profile.getKey(), ruleKey);
+  }
+
+  public QProfileTester activateRule(String profileKey, String ruleKey) {
+    ActivateRuleWsRequest request = ActivateRuleWsRequest.builder()
+      .setProfileKey(profileKey)
+      .setRuleKey(ruleKey)
+      .build();
+    service().activateRule(request);
+    return this;
+  }
+
+  public QProfileTester deactivateRule(QualityProfile profile, String ruleKey) {
+    service().deactivateRule(profile.getKey(), ruleKey);
+    return this;
+  }
+
+  public QProfileTester assertThatNumberOfActiveRulesEqualsTo(QualityProfile profile, int expectedActiveRules) {
+    return assertThatNumberOfActiveRulesEqualsTo(profile.getKey(), expectedActiveRules);
+  }
+
+  public QProfileTester assertThatNumberOfActiveRulesEqualsTo(String profileKey, int expectedActiveRules) {
+    try {
+      List<String> facetIds = asList("active_severities", "repositories", "languages", "severities", "statuses", "types");
+      SearchWsRequest request = new SearchWsRequest()
+        .setQProfile(profileKey)
+        .setActivation(true)
+        .setFacets(facetIds)
+        .setFields(singletonList("actives"));
+      Rules.SearchResponse response = session.wsClient().rules().search(request);
+
+      // assume that expectedActiveRules fits in first page of results
+      assertThat(response.getRulesCount()).isEqualTo(expectedActiveRules);
+      assertThat(response.getTotal()).isEqualTo(expectedActiveRules);
+      assertThat(response.getActives().getActives()).as(response.toString()).hasSize(expectedActiveRules);
+
+      // verify facets
+      assertThat(response.getFacets().getFacetsCount()).isEqualTo(facetIds.size());
+      response.getFacets().getFacetsList().forEach(facet -> {
+        long total = facet.getValuesList().stream()
+          .mapToLong(Common.FacetValue::getCount)
+          .sum();
+        assertThat(total).as("Facet " + facet.getProperty()).isEqualTo((long) expectedActiveRules);
+      });
+    } catch (HttpException e) {
+      if (expectedActiveRules == 0 && e.code() == 404) {
+        // profile does not exist, do nothing
+        return this;
+      }
+      throw e;
+    }
+    return this;
+  }
+}
diff --git a/it/it-tests/src/test/java/org/sonarqube/test/Session.java b/it/it-tests/src/test/java/org/sonarqube/test/Session.java
new file mode 100644 (file)
index 0000000..f997644
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * SonarQube
+ * Copyright (C) 2009-2017 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.sonarqube.test;
+
+import org.sonarqube.ws.client.WsClient;
+
+public interface Session {
+
+  WsClient wsClient();
+
+  GroupTester groups();
+
+  OrganizationTester organizations();
+
+  QProfileTester qProfiles();
+
+  UserTester users();
+
+}
diff --git a/it/it-tests/src/test/java/org/sonarqube/test/Tester.java b/it/it-tests/src/test/java/org/sonarqube/test/Tester.java
new file mode 100644 (file)
index 0000000..a5b31a4
--- /dev/null
@@ -0,0 +1,191 @@
+/*
+ * SonarQube
+ * Copyright (C) 2009-2017 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.sonarqube.test;
+
+import com.sonar.orchestrator.Orchestrator;
+import javax.annotation.Nullable;
+import org.junit.rules.ExternalResource;
+import org.sonarqube.ws.client.WsClient;
+import org.sonarqube.ws.client.setting.SetRequest;
+import pageobjects.Navigation;
+import util.selenium.Selenese;
+
+import static util.ItUtils.newUserWsClient;
+
+public class Tester extends ExternalResource implements Session {
+
+  private final Orchestrator orchestrator;
+
+  // configuration before startup
+  private boolean disableOrganizations = false;
+  private boolean enableOnBoardingTutorials = false;
+
+  // initialized in #before()
+  private boolean beforeCalled = false;
+  private Session rootSession;
+
+  public Tester(Orchestrator orchestrator) {
+    this.orchestrator = orchestrator;
+  }
+
+  public Tester disableOrganizations() {
+    verifyNotStarted();
+    disableOrganizations = true;
+    return this;
+  }
+
+  public Tester enableOnBoardingTutorials() {
+    verifyNotStarted();
+    enableOnBoardingTutorials = true;
+    return this;
+  }
+
+  @Override
+  protected void before() {
+    verifyNotStarted();
+    rootSession = new SessionImpl(orchestrator, "admin", "admin");
+
+    if (!disableOrganizations) {
+      organizations().enableSupport();
+    }
+
+    if (!enableOnBoardingTutorials) {
+      rootSession.wsClient().settings().set(SetRequest.builder()
+        .setKey("sonar.onboardingTutorial.showToNewUsers")
+        .setValue("false")
+        .build());
+      rootSession.wsClient().users().skipOnboardingTutorial();
+    }
+
+    beforeCalled = true;
+  }
+
+  @Override
+  protected void after() {
+    if (!disableOrganizations) {
+      organizations().deleteNonGuardedOrganizations();
+    }
+    users().deleteAll();
+  }
+
+  public Session asAnonymous() {
+    return as(null, null);
+  }
+
+  public Session as(String login) {
+    return as(login, login);
+  }
+
+  public Session as(String login, String password) {
+    verifyStarted();
+    return new SessionImpl(orchestrator, login, password);
+  }
+
+  /**
+   * Open a new browser session. Cookies are deleted.
+   */
+  public Navigation openBrowser() {
+    verifyStarted();
+    return Navigation.create(orchestrator);
+  }
+
+  /**
+   * @deprecated use Selenide tests with {@link #openBrowser()}
+   */
+  @Deprecated
+  public Tester runHtmlTests(String... htmlTests) {
+    Selenese.runSelenese(orchestrator, htmlTests);
+    return this;
+  }
+
+  private void verifyNotStarted() {
+    if (beforeCalled) {
+      throw new IllegalStateException("Orchestrator should not be already started");
+    }
+  }
+
+  private void verifyStarted() {
+    if (!beforeCalled) {
+      throw new IllegalStateException("Orchestrator is not started yet");
+    }
+  }
+
+  /**
+   * Web service client configured with root access
+   */
+  @Override
+  public WsClient wsClient() {
+    verifyStarted();
+    return rootSession.wsClient();
+  }
+
+  @Override
+  public GroupTester groups() {
+    return rootSession.groups();
+  }
+
+  @Override
+  public OrganizationTester organizations() {
+    return rootSession.organizations();
+  }
+
+  @Override
+  public QProfileTester qProfiles() {
+    return rootSession.qProfiles();
+  }
+
+  @Override
+  public UserTester users() {
+    return rootSession.users();
+  }
+
+  private static class SessionImpl implements Session {
+    private final WsClient client;
+
+    private SessionImpl(Orchestrator orchestrator, @Nullable String login, @Nullable String password) {
+      this.client = newUserWsClient(orchestrator, login, password);
+    }
+
+    @Override
+    public WsClient wsClient() {
+      return client;
+    }
+
+    @Override
+    public GroupTester groups() {
+      return new GroupTester(this);
+    }
+
+    @Override
+    public OrganizationTester organizations() {
+      return new OrganizationTester(this);
+    }
+
+    @Override
+    public QProfileTester qProfiles() {
+      return new QProfileTester(this);
+    }
+
+    @Override
+    public UserTester users() {
+      return new UserTester(this);
+    }
+  }
+}
diff --git a/it/it-tests/src/test/java/org/sonarqube/test/UserTester.java b/it/it-tests/src/test/java/org/sonarqube/test/UserTester.java
new file mode 100644 (file)
index 0000000..baa2ed3
--- /dev/null
@@ -0,0 +1,101 @@
+/*
+ * SonarQube
+ * Copyright (C) 2009-2017 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.sonarqube.test;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
+import org.sonarqube.ws.Organizations;
+import org.sonarqube.ws.WsUsers;
+import org.sonarqube.ws.WsUsers.CreateWsResponse.User;
+import org.sonarqube.ws.client.PostRequest;
+import org.sonarqube.ws.client.user.CreateRequest;
+import org.sonarqube.ws.client.user.SearchRequest;
+import org.sonarqube.ws.client.user.UsersService;
+import org.sonarqube.ws.client.usergroup.AddUserWsRequest;
+
+import static java.util.Arrays.stream;
+
+public class UserTester {
+
+  private static final AtomicInteger ID_GENERATOR = new AtomicInteger();
+
+  private final Session session;
+
+  UserTester(Session session) {
+    this.session = session;
+  }
+
+  void deleteAll() {
+    session.wsClient().users().search(SearchRequest.builder().build()).getUsersList()
+      .stream()
+      .filter(u -> !"admin".equals(u.getLogin()))
+      .forEach(u -> {
+        PostRequest request = new PostRequest("api/users/deactivate").setParam("login", u.getLogin());
+        session.wsClient().wsConnector().call(request);
+      });
+  }
+
+  @SafeVarargs
+  public final User generate(Consumer<CreateRequest.Builder>... populators) {
+    int id = ID_GENERATOR.getAndIncrement();
+    String login = "login" + id;
+    CreateRequest.Builder request = CreateRequest.builder()
+      .setLogin(login)
+      .setPassword(login)
+      .setName("name" + id)
+      .setEmail(id + "@test.com");
+    stream(populators).forEach(p -> p.accept(request));
+    return service().create(request.build()).getUser();
+  }
+
+  @SafeVarargs
+  public final User generateAdministrator(Consumer<CreateRequest.Builder>... populators) {
+    User user = generate(populators);
+    session.wsClient().permissions().addUser(new org.sonarqube.ws.client.permission.AddUserWsRequest().setLogin(user.getLogin()).setPermission("admin"));
+    session.wsClient().userGroups().addUser(org.sonarqube.ws.client.usergroup.AddUserWsRequest.builder().setLogin(user.getLogin()).setName("sonar-administrators").build());
+    return user;
+  }
+
+  @SafeVarargs
+  public final User generateAdministrator(Organizations.Organization organization, Consumer<CreateRequest.Builder>... populators) {
+    User user = generate(populators);
+    session.wsClient().organizations().addMember(organization.getKey(), user.getLogin());
+    session.wsClient().userGroups().addUser(AddUserWsRequest.builder()
+      .setOrganization(organization.getKey())
+      .setLogin(user.getLogin())
+      .setName("Owners")
+      .build());
+    return user;
+  }
+
+  public UsersService service() {
+    return session.wsClient().users();
+  }
+
+  public Optional<WsUsers.SearchWsResponse.User> getByLogin(String login) {
+    List<WsUsers.SearchWsResponse.User> users = session.wsClient().users().search(SearchRequest.builder().setQuery(login).build()).getUsersList();
+    if (users.size() == 1) {
+      return Optional.of(users.get(0));
+    }
+    return Optional.empty();
+  }
+}
index 00fa6413a82d058868b6bb96008c5ff39b00ff2d..d601dbac1e0833f27a0343d06ed9888ddd3b6420 100644 (file)
@@ -25,7 +25,7 @@ import static com.codeborne.selenide.Condition.exist;
 import static com.codeborne.selenide.Condition.visible;
 import static com.codeborne.selenide.Selenide.$;
 
-public class EncryptionPage {
+public class EncryptionPage extends Navigation {
 
   public EncryptionPage() {
     $("#encryption-page").should(exist);
index 5123f5f91a650712b0bfb9265ed222446aca9719..c772b79a1c24c5543cfe0020da69c42d621a9139 100644 (file)
@@ -22,36 +22,57 @@ package pageobjects;
 import com.codeborne.selenide.Condition;
 import com.codeborne.selenide.Selenide;
 import com.codeborne.selenide.SelenideElement;
+import com.codeborne.selenide.WebDriverRunner;
 import com.sonar.orchestrator.Orchestrator;
 import java.io.UnsupportedEncodingException;
 import java.net.URLEncoder;
+import java.util.function.Consumer;
 import javax.annotation.Nullable;
-import org.junit.rules.ExternalResource;
 import org.openqa.selenium.By;
+import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.html5.WebStorage;
+import org.sonarqube.test.Tester;
 import pageobjects.issues.IssuesPage;
 import pageobjects.licenses.LicensesPage;
 import pageobjects.organization.MembersPage;
 import pageobjects.projects.ProjectsPage;
 import pageobjects.settings.SettingsPage;
 
-import static com.codeborne.selenide.Condition.hasText;
+import static com.codeborne.selenide.Condition.visible;
 import static com.codeborne.selenide.Selenide.$;
+import static com.codeborne.selenide.Selenide.clearBrowserLocalStorage;
 import static com.codeborne.selenide.Selenide.page;
 
-public class Navigation extends ExternalResource {
+public class Navigation {
 
-  public static Navigation get(Orchestrator orchestrator) {
-    SelenideConfig.configure(orchestrator);
-    return new Navigation();
+  public Navigation() {
+    $("#content").shouldBe(Condition.exist);
   }
 
-  @Override
-  protected void before() throws Throwable {
-    SelenideConfig.getWebDriver().manage().deleteAllCookies();
-    openHomepage();
+  /**
+   * @deprecated use {@link Tester#openBrowser()}
+   */
+  @Deprecated
+  public static Navigation create(Orchestrator orchestrator) {
+    WebDriver driver = SelenideConfig.configure(orchestrator);
+    driver.manage().deleteAllCookies();
+    clearStorage(d -> d.getLocalStorage().clear());
+    clearStorage(d -> d.getSessionStorage().clear());
+    clearStorage(d -> clearBrowserLocalStorage());
+    return Selenide.open("/", Navigation.class);
   }
 
-  public Navigation openHomepage() {
+  private static void clearStorage(Consumer<WebStorage> cleaner) {
+    try {
+      cleaner.accept((WebStorage) WebDriverRunner.getWebDriver());
+    } catch (Exception e) {
+      // ignore, it may occur when the first test opens browser. No pages are loaded
+      // and local/session storages are not available yet.
+      // Example with Chrome: "Failed to read the 'localStorage' property from 'Window': Storage is disabled inside 'data:' URLs."
+    }
+  }
+
+  public Navigation openHome() {
     return open("/", Navigation.class);
   }
 
@@ -152,12 +173,14 @@ public class Navigation extends ExternalResource {
     return Selenide.open(relativeUrl, pageObjectClassClass);
   }
 
-  public void shouldBeLoggedIn() {
+  public Navigation shouldBeLoggedIn() {
     loggedInDropdown().should(Condition.visible);
+    return this;
   }
 
-  public void shouldNotBeLoggedIn() {
+  public Navigation shouldNotBeLoggedIn() {
     logInLink().should(Condition.visible);
+    return this;
   }
 
   public LoginPage logIn() {
@@ -203,8 +226,9 @@ public class Navigation extends ExternalResource {
     return $(".js-user-authenticated");
   }
 
-  public void shouldBeRedirectToLogin() {
-    $("#content").should(hasText("Log In to SonarQube"));
+  public Navigation shouldBeRedirectedToLogin() {
+    $("#login_form").should(visible);
+    return this;
   }
 
 }
index 82f4b4d3f4aa03cc525f63c9e8b1e637cfc8b2f6..61704e7a88f58703cff5c596fdeb6749278c3d19 100644 (file)
@@ -24,7 +24,7 @@ import static com.codeborne.selenide.Condition.text;
 import static com.codeborne.selenide.Condition.visible;
 import static com.codeborne.selenide.Selenide.$;
 
-public class NotificationsPage {
+public class NotificationsPage extends Navigation {
 
   private final String EMAIL = "EmailNotificationChannel";
 
index a1d02f4e12fa6853187b6ac86cbad40846888a54..ee90dd59849e9446a3ad2af9abec7c632f554c84 100644 (file)
@@ -28,7 +28,7 @@ import org.openqa.selenium.By;
 import static com.codeborne.selenide.Selenide.$;
 import static com.codeborne.selenide.Selenide.$$;
 
-public class RulesPage {
+public class RulesPage extends Navigation {
 
   public RulesPage() {
     $(By.cssSelector(".coding-rules")).should(Condition.exist);
index 1bbabd35fdeb7ce35d73173c262f3f03b2ade6d7..e5281dd88b54a58454b2fe88a53826ee98924999 100644 (file)
@@ -234,9 +234,9 @@ public class ItUtils {
 
   public static void setServerProperty(Orchestrator orchestrator, @Nullable String componentKey, String key, @Nullable String value) {
     if (value == null) {
-      newAdminWsClient(orchestrator).settingsService().reset(ResetRequest.builder().setKeys(key).setComponent(componentKey).build());
+      newAdminWsClient(orchestrator).settings().reset(ResetRequest.builder().setKeys(key).setComponent(componentKey).build());
     } else {
-      newAdminWsClient(orchestrator).settingsService().set(SetRequest.builder().setKey(key).setValue(value).setComponent(componentKey).build());
+      newAdminWsClient(orchestrator).settings().set(SetRequest.builder().setKey(key).setValue(value).setComponent(componentKey).build());
     }
   }
 
@@ -248,7 +248,7 @@ public class ItUtils {
 
   public static void resetSettings(Orchestrator orchestrator, @Nullable String componentKey, String... keys) {
     if (keys.length > 0) {
-      newAdminWsClient(orchestrator).settingsService().reset(ResetRequest.builder().setKeys(keys).setComponent(componentKey).build());
+      newAdminWsClient(orchestrator).settings().reset(ResetRequest.builder().setKeys(keys).setComponent(componentKey).build());
     }
   }
 
@@ -476,31 +476,31 @@ public class ItUtils {
   }
 
   public static void expectBadRequestError(Runnable runnable) {
-    expectHttpError(runnable, 400);
+    expectHttpError(400, runnable);
   }
 
   public static void expectMissingError(Runnable runnable) {
-    expectHttpError(runnable, 404);
+    expectHttpError(404, runnable);
   }
   /**
    * Missing permissions
    */
   public static void expectForbiddenError(Runnable runnable) {
-    expectHttpError(runnable, 403);
+    expectHttpError(403, runnable);
   }
 
   /**
    * Not authenticated
    */
   public static void expectUnauthorizedError(Runnable runnable) {
-    expectHttpError(runnable, 401);
+    expectHttpError(401, runnable);
   }
 
   public static void expectNotFoundError(Runnable runnable) {
-    expectHttpError(runnable, 404);
+    expectHttpError(404, runnable);
   }
 
-  private static void expectHttpError(Runnable runnable, int expectedCode) {
+  public static void expectHttpError(int expectedCode, Runnable runnable) {
     try {
       runnable.run();
       Assert.fail("Ws call should have failed");
@@ -508,4 +508,14 @@ public class ItUtils {
       assertThat(e.code()).isEqualTo(expectedCode);
     }
   }
+
+  public static void expectHttpError(int expectedCode, String expectedMessage, Runnable runnable) {
+    try {
+      runnable.run();
+      Assert.fail("Ws call should have failed");
+    } catch (org.sonarqube.ws.client.HttpException e) {
+      assertThat(e.code()).isEqualTo(expectedCode);
+      assertThat(e.getMessage()).contains(expectedMessage);
+    }
+  }
 }
diff --git a/it/it-tests/src/test/java/util/OrganizationRule.java b/it/it-tests/src/test/java/util/OrganizationRule.java
deleted file mode 100644 (file)
index 8034ffa..0000000
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * SonarQube
- * Copyright (C) 2009-2017 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 util;
-
-import com.sonar.orchestrator.Orchestrator;
-import com.sonar.orchestrator.http.HttpMethod;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.function.Consumer;
-import javax.annotation.Nullable;
-import org.junit.rules.ExternalResource;
-import org.sonarqube.ws.Organizations;
-import org.sonarqube.ws.Organizations.Organization;
-import org.sonarqube.ws.WsUsers;
-import org.sonarqube.ws.client.HttpException;
-import org.sonarqube.ws.client.WsClient;
-import org.sonarqube.ws.client.organization.CreateWsRequest;
-import org.sonarqube.ws.client.organization.OrganizationService;
-import org.sonarqube.ws.client.organization.SearchMembersWsRequest;
-import org.sonarqube.ws.client.organization.SearchWsRequest;
-import org.sonarqube.ws.client.user.GroupsRequest;
-
-import static java.util.Arrays.stream;
-import static org.assertj.core.api.Assertions.assertThat;
-import static util.ItUtils.newAdminWsClient;
-
-public class OrganizationRule extends ExternalResource implements OrganizationSupport {
-
-  private final Orchestrator orchestrator;
-  private OrganizationSupport rootSupport;
-
-  public OrganizationRule(Orchestrator orchestrator) {
-    this.orchestrator = orchestrator;
-  }
-
-  @Override
-  protected void before() {
-    enableSupport();
-    rootSupport = new OrganizationSupportImpl(newAdminWsClient(orchestrator));
-  }
-
-  @Override
-  protected void after() {
-    deleteOrganizations();
-  }
-
-  private void enableSupport() {
-    orchestrator.getServer()
-      .newHttpCall("api/organizations/enable_support")
-      .setMethod(HttpMethod.POST)
-      .setAdminCredentials()
-      .execute();
-  }
-
-  public void deleteOrganizations() {
-    rootSupport.getWsService().search(SearchWsRequest.builder().build()).getOrganizationsList()
-      .stream()
-      .filter(o -> !o.getKey().equals("default-organization"))
-      .forEach(organization -> rootSupport.getWsService().delete(organization.getKey()));
-  }
-
-  public OrganizationSupport as(String login, String password) {
-    return new OrganizationSupportImpl(ItUtils.newUserWsClient(orchestrator, login, password));
-  }
-
-  public OrganizationSupport asAnonymous() {
-    return as(null, null);
-  }
-
-  @Override
-  public OrganizationService getWsService() {
-    return rootSupport.getWsService();
-  }
-
-  @Override
-  public Organization create(Consumer<CreateWsRequest.Builder>... populators) {
-    return rootSupport.create(populators);
-  }
-
-  @Override
-  public OrganizationSupport delete(Organization organization) {
-    return rootSupport.delete(organization);
-  }
-
-  public OrganizationRule assertThatOrganizationDoesNotExist(String organizationKey) {
-    SearchWsRequest request = new SearchWsRequest.Builder().setOrganizations(organizationKey).build();
-    Organizations.SearchWsResponse searchWsResponse = getWsService().search(request);
-    assertThat(searchWsResponse.getOrganizationsList()).isEmpty();
-    return this;
-  }
-
-  public OrganizationRule assertThatMemberOf(@Nullable Organization organization, WsUsers.CreateWsResponse.User user) {
-    verifyOrganizationMembership(organization, user, true);
-    verifyMembersGroupMembership(user, organization, true);
-    return this;
-  }
-
-  public OrganizationRule assertThatNotMemberOf(@Nullable Organization organization, WsUsers.CreateWsResponse.User user) {
-    verifyOrganizationMembership(organization, user, false);
-    try {
-      verifyMembersGroupMembership(user, organization, false);
-    } catch (HttpException e) {
-      // do not fail if user does not exist
-      if (e.code() != 404) {
-        throw e;
-      }
-    }
-    return this;
-  }
-
-  private void verifyOrganizationMembership(@Nullable Organization organization, WsUsers.CreateWsResponse.User user, boolean isMember) {
-    List<Organizations.User> users = getWsService().searchMembers(new SearchMembersWsRequest()
-      .setQuery(user.getLogin())
-      .setSelected("selected")
-      .setOrganization(organization != null ? organization.getKey() : null))
-      .getUsersList();
-    assertThat(users).hasSize(isMember ? 1 : 0);
-  }
-
-  private void verifyMembersGroupMembership(WsUsers.CreateWsResponse.User user, @Nullable Organization organization, boolean isMember) {
-    List<WsUsers.GroupsWsResponse.Group> groups = newAdminWsClient(orchestrator).users().groups(GroupsRequest.builder()
-      .setLogin(user.getLogin())
-      .setOrganization(organization != null ? organization.getKey() : null)
-      .setQuery("Members")
-      .setSelected("selected")
-      .build())
-      .getGroupsList();
-    assertThat(groups).hasSize(isMember ? 1 : 0);
-  }
-
-  private static class OrganizationSupportImpl implements OrganizationSupport {
-    private static final AtomicInteger ID_GENERATOR = new AtomicInteger();
-    private final WsClient wsClient;
-
-    private OrganizationSupportImpl(WsClient wsClient) {
-      this.wsClient = wsClient;
-    }
-
-    @Override
-    public OrganizationService getWsService() {
-      return wsClient.organizations();
-    }
-
-    @Override
-    public Organization create(Consumer<CreateWsRequest.Builder>... populators) {
-      int id = ID_GENERATOR.getAndIncrement();
-      CreateWsRequest.Builder request = new CreateWsRequest.Builder()
-        .setKey("org" + id)
-        .setName("Org " + id);
-      stream(populators).forEach(p -> p.accept(request));
-      return getWsService().create(request.build()).getOrganization();
-    }
-
-    @Override
-    public OrganizationSupport delete(Organization organization) {
-      getWsService().delete(organization.getKey());
-      return this;
-    }
-  }
-}
diff --git a/it/it-tests/src/test/java/util/OrganizationSupport.java b/it/it-tests/src/test/java/util/OrganizationSupport.java
deleted file mode 100644 (file)
index 9b8a6e3..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * SonarQube
- * Copyright (C) 2009-2017 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 util;
-
-import java.util.function.Consumer;
-import org.sonarqube.ws.Organizations.Organization;
-import org.sonarqube.ws.client.organization.CreateWsRequest;
-import org.sonarqube.ws.client.organization.OrganizationService;
-
-public interface OrganizationSupport {
-
-  OrganizationService getWsService();
-
-  /**
-   * Create organization with randomly generated key and name
-   */
-  Organization create(Consumer<CreateWsRequest.Builder>... populators);
-
-  OrganizationSupport delete(Organization organization);
-
-}
diff --git a/it/it-tests/src/test/java/util/QualityProfileRule.java b/it/it-tests/src/test/java/util/QualityProfileRule.java
deleted file mode 100644 (file)
index a8904f3..0000000
+++ /dev/null
@@ -1,178 +0,0 @@
-/*
- * SonarQube
- * Copyright (C) 2009-2017 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 util;
-
-import com.sonar.orchestrator.Orchestrator;
-import java.util.List;
-import java.util.function.Consumer;
-import org.junit.rules.ExternalResource;
-import org.sonarqube.ws.Common;
-import org.sonarqube.ws.Organizations;
-import org.sonarqube.ws.QualityProfiles.CreateWsResponse.QualityProfile;
-import org.sonarqube.ws.Rules;
-import org.sonarqube.ws.client.HttpException;
-import org.sonarqube.ws.client.WsClient;
-import org.sonarqube.ws.client.qualityprofile.ActivateRuleWsRequest;
-import org.sonarqube.ws.client.qualityprofile.CreateRequest;
-import org.sonarqube.ws.client.qualityprofile.DeleteRequest;
-import org.sonarqube.ws.client.qualityprofile.QualityProfilesService;
-import org.sonarqube.ws.client.rule.SearchWsRequest;
-
-import static java.util.Arrays.asList;
-import static java.util.Arrays.stream;
-import static java.util.Collections.singletonList;
-import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
-import static org.assertj.core.api.Assertions.assertThat;
-import static util.ItUtils.newUserWsClient;
-import static util.ItUtils.newWsClient;
-
-public class QualityProfileRule extends ExternalResource implements QualityProfileSupport {
-
-  private final Orchestrator orchestrator;
-  private QualityProfileSupport support;
-
-  public QualityProfileRule(Orchestrator orchestrator) {
-    this.orchestrator = orchestrator;
-  }
-
-  @Override
-  protected void before() throws Throwable {
-    support = new QualityProfileSupportImpl(ItUtils.newAdminWsClient(orchestrator));
-  }
-
-  public QualityProfileSupport as(String login, String password) {
-    return new QualityProfileSupportImpl(newUserWsClient(orchestrator, login, password));
-  }
-
-  public QualityProfileSupport asAnonymous() {
-    return new QualityProfileSupportImpl(newWsClient(orchestrator));
-  }
-
-  @Override
-  public QualityProfilesService getWsService() {
-    return support.getWsService();
-  }
-
-  @Override
-  public QualityProfile createXooProfile(Organizations.Organization organization, Consumer<CreateRequest.Builder>... populators) {
-    return support.createXooProfile(organization, populators);
-  }
-
-  @Override
-  public QualityProfileSupport delete(String profileKey) {
-    return support.delete(profileKey);
-  }
-
-  @Override
-  public QualityProfileSupport activateRule(String profileKey, String ruleKey) {
-    return support.activateRule(profileKey, ruleKey);
-  }
-
-  @Override
-  public QualityProfileSupport deactivateRule(String profileKey, String ruleKey) {
-    return support.deactivateRule(profileKey, ruleKey);
-  }
-
-  @Override
-  public QualityProfileSupport assertThatNumberOfActiveRulesEqualsTo(String profileKey, int expectedActiveRules) {
-    return support.assertThatNumberOfActiveRulesEqualsTo(profileKey, expectedActiveRules);
-  }
-
-  private static class QualityProfileSupportImpl implements QualityProfileSupport {
-
-    private final WsClient wsClient;
-
-    private QualityProfileSupportImpl(WsClient wsClient) {
-      this.wsClient = wsClient;
-    }
-
-    @Override
-    public QualityProfilesService getWsService() {
-      return wsClient.qualityProfiles();
-    }
-
-    @Override
-    public QualityProfile createXooProfile(Organizations.Organization organization, Consumer<CreateRequest.Builder>... populators) {
-      CreateRequest.Builder request = CreateRequest.builder()
-        .setOrganizationKey(organization.getKey())
-        .setLanguage("xoo")
-        .setProfileName(randomAlphanumeric(10));
-      stream(populators).forEach(p -> p.accept(request));
-      return getWsService().create(request.build()).getProfile();
-    }
-
-    @Override
-    public QualityProfileSupport delete(String profileKey) {
-      getWsService().delete(new DeleteRequest(profileKey));
-      return this;
-    }
-
-    @Override
-    public QualityProfileSupport activateRule(String profileKey, String ruleKey) {
-      ActivateRuleWsRequest request = ActivateRuleWsRequest.builder()
-        .setProfileKey(profileKey)
-        .setRuleKey(ruleKey)
-        .build();
-      getWsService().activateRule(request);
-      return this;
-    }
-
-    @Override
-    public QualityProfileSupport deactivateRule(String profileKey, String ruleKey) {
-      getWsService().deactivateRule(profileKey, ruleKey);
-      return this;
-    }
-
-    @Override
-    public QualityProfileSupport assertThatNumberOfActiveRulesEqualsTo(String profileKey, int expectedActiveRules) {
-      try {
-        List<String> facetIds = asList("active_severities", "repositories", "languages", "severities", "statuses", "types");
-        SearchWsRequest request = new SearchWsRequest()
-          .setQProfile(profileKey)
-          .setActivation(true)
-          .setFacets(facetIds)
-          .setFields(singletonList("actives"));
-        Rules.SearchResponse response = wsClient.rules().search(request);
-
-        // assume that expectedActiveRules fits in first page of results
-        assertThat(response.getRulesCount()).isEqualTo(expectedActiveRules);
-        assertThat(response.getTotal()).isEqualTo(expectedActiveRules);
-        assertThat(response.getActives().getActives()).as(response.toString()).hasSize(expectedActiveRules);
-
-        // verify facets
-        assertThat(response.getFacets().getFacetsCount()).isEqualTo(facetIds.size());
-        response.getFacets().getFacetsList().forEach(facet -> {
-          long total = facet.getValuesList().stream()
-            .mapToLong(Common.FacetValue::getCount)
-            .sum();
-          assertThat(total).as("Facet " + facet.getProperty()).isEqualTo((long) expectedActiveRules);
-        });
-      } catch (HttpException e) {
-        if (expectedActiveRules == 0 && e.code() == 404) {
-          // profile does not exist, do nothing
-          return this;
-        }
-        throw e;
-      }
-      return this;
-    }
-
-  }
-}
diff --git a/it/it-tests/src/test/java/util/QualityProfileSupport.java b/it/it-tests/src/test/java/util/QualityProfileSupport.java
deleted file mode 100644 (file)
index 647d314..0000000
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * SonarQube
- * Copyright (C) 2009-2017 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 util;
-
-import java.util.function.Consumer;
-import org.sonarqube.ws.Organizations;
-import org.sonarqube.ws.QualityProfiles;
-import org.sonarqube.ws.QualityProfiles.CreateWsResponse.QualityProfile;
-import org.sonarqube.ws.client.qualityprofile.CreateRequest;
-import org.sonarqube.ws.client.qualityprofile.QualityProfilesService;
-
-public interface QualityProfileSupport {
-
-  QualityProfilesService getWsService();
-
-  QualityProfile createXooProfile(Organizations.Organization organization, Consumer<CreateRequest.Builder>... populators);
-
-  QualityProfileSupport delete(String profileKey);
-
-  default QualityProfileSupport delete(QualityProfile profile) {
-    return delete(profile.getKey());
-  }
-
-  default QualityProfileSupport delete(QualityProfiles.SearchWsResponse.QualityProfile profile) {
-    return delete(profile.getKey());
-  }
-
-  QualityProfileSupport activateRule(String profileKey, String ruleKey);
-
-  default QualityProfileSupport activateRule(QualityProfile profile, String ruleKey) {
-    return activateRule(profile.getKey(), ruleKey);
-  }
-
-  default QualityProfileSupport activateRule(QualityProfiles.SearchWsResponse.QualityProfile profile, String ruleKey) {
-    return activateRule(profile.getKey(), ruleKey);
-  }
-
-  QualityProfileSupport deactivateRule(String profileKey, String ruleKey);
-
-  default QualityProfileSupport deactivateRule(QualityProfile profile, String ruleKey) {
-    return deactivateRule(profile.getKey(), ruleKey);
-  }
-
-  default QualityProfileSupport deactivateRule(QualityProfiles.SearchWsResponse.QualityProfile profile, String ruleKey) {
-    return deactivateRule(profile.getKey(), ruleKey);
-  }
-
-  QualityProfileSupport assertThatNumberOfActiveRulesEqualsTo(String profileKey, int expectedActiveRules);
-
-  default QualityProfileSupport assertThatNumberOfActiveRulesEqualsTo(QualityProfile profile, int expectedActiveRules) {
-    return assertThatNumberOfActiveRulesEqualsTo(profile.getKey(), expectedActiveRules);
-  }
-
-  default QualityProfileSupport assertThatNumberOfActiveRulesEqualsTo(QualityProfiles.SearchWsResponse.QualityProfile profile, int expectedActiveRules) {
-    return assertThatNumberOfActiveRulesEqualsTo(profile.getKey(), expectedActiveRules);
-  }
-}
index de0bce71faafb860a037cafe3dae1e6b271411b0..36beb068231ee8be06ceebe8f72847b2feeb8913 100644 (file)
@@ -115,15 +115,17 @@ public class UserRule extends ExternalResource implements GroupManagement {
   }
 
   /**
-   * Create user with randomly generated values
+   * Create user with randomly generated values. By default password is the login.
    */
-  public WsUsers.CreateWsResponse.User createUser(Consumer<CreateRequest.Builder>... populators) {
+  @SafeVarargs
+  public final WsUsers.CreateWsResponse.User generate(Consumer<CreateRequest.Builder>... populators) {
     int id = ID_GENERATOR.getAndIncrement();
+    String login = "login" + id;
     CreateRequest.Builder request = CreateRequest.builder()
-      .setLogin("login" + id)
+      .setLogin(login)
       .setName("name" + id)
       .setEmail(id + "@test.com")
-      .setPassword("password" + id);
+      .setPassword(login);
     stream(populators).forEach(p -> p.accept(request));
     return adminWsClient().users().create(request.build()).getUser();
   }
@@ -133,7 +135,7 @@ public class UserRule extends ExternalResource implements GroupManagement {
   }
 
   public WsUsers.CreateWsResponse.User createAdministrator(Organizations.Organization organization, String password) {
-    WsUsers.CreateWsResponse.User user = createUser(p -> p.setPassword(password));
+    WsUsers.CreateWsResponse.User user = generate(p -> p.setPassword(password));
     adminWsClient.organizations().addMember(organization.getKey(), user.getLogin());
     forOrganization(organization.getKey()).associateGroupsToUser(user.getLogin(), "Owners");
     return user;
@@ -169,11 +171,11 @@ public class UserRule extends ExternalResource implements GroupManagement {
   }
 
   public void setRoot(String login) {
-    adminWsClient().rootService().setRoot(login);
+    adminWsClient().roots().setRoot(login);
   }
 
   public void unsetRoot(String login) {
-    adminWsClient().rootService().unsetRoot(login);
+    adminWsClient().roots().unsetRoot(login);
   }
 
   public Optional<Users.User> getUserByLogin(String login) {
index 88d01cd0da4d82081f23dbfd247eefa7db6580e2..1ed2b8a9018d4b5ba8e2fadcda5108029f6846f5 100644 (file)
 </tr>
 </thead>
 <tbody>
-<tr>
-       <td>open</td>
-       <td>/sessions/logout</td>
-       <td></td>
-</tr>
 <tr>
        <td>open</td>
        <td>/sessions/login</td>
 <tr>
        <td>type</td>
        <td>password</td>
-       <td>root-user</td>
+       <td>admin2</td>
 </tr>
 <tr>
        <td>type</td>
        <td>login</td>
-       <td>root-user</td>
+       <td>admin2</td>
 </tr>
 <tr>
        <td>clickAndWait</td>
index 41fae4ae338b56acee6f6f338741226f4a7edb31..a6716b8c06acd39e2c75345e996cea9f06b04ebe 100644 (file)
 </tr>
 </thead>
 <tbody>
-<tr>
-       <td>open</td>
-       <td>/sessions/logout</td>
-       <td></td>
-</tr>
 <tr>
        <td>open</td>
        <td>/sessions/login</td>
 <tr>
        <td>type</td>
        <td>password</td>
-       <td>root-user</td>
+       <td>admin2</td>
 </tr>
 <tr>
        <td>type</td>
        <td>login</td>
-       <td>root-user</td>
+       <td>admin2</td>
 </tr>
 <tr>
        <td>clickAndWait</td>
index 4f3a2793d2997168234d62c16ba98503a8cc4a7e..9610b0db66c2184028340fcd57af0424302b9b41 100644 (file)
 </tr>
 </thead>
 <tbody>
-<tr>
-       <td>open</td>
-       <td>/sessions/logout</td>
-       <td></td>
-</tr>
 <tr>
        <td>open</td>
        <td>/sessions/login</td>
 <tr>
        <td>type</td>
        <td>password</td>
-       <td>root-user</td>
+       <td>admin2</td>
 </tr>
 <tr>
        <td>type</td>
        <td>login</td>
-       <td>root-user</td>
+       <td>admin2</td>
 </tr>
 <tr>
        <td>clickAndWait</td>
index 3ae2ebd71d291e84f2fe2a4eac382e53be1a4de7..5da4d40ca0c2d580e54673bd97ee1bc0380abf63 100644 (file)
 </tr>
 </thead>
 <tbody>
-<tr>
-       <td>open</td>
-       <td>/sessions/logout</td>
-       <td></td>
-</tr>
 <tr>
        <td>open</td>
        <td>/sessions/login</td>
 <tr>
        <td>type</td>
        <td>password</td>
-       <td>root-user</td>
+       <td>admin2</td>
 </tr>
 <tr>
        <td>type</td>
        <td>login</td>
-       <td>root-user</td>
+       <td>admin2</td>
 </tr>
 <tr>
        <td>clickAndWait</td>
index 807f14a50c66e2e416f988b18384b25bb404c697..dd2d21ba31f8fedbf236640209edba17c0265fb9 100644 (file)
 </tr>
 </thead>
 <tbody>
-<tr>
-       <td>open</td>
-       <td>/sessions/logout</td>
-       <td></td>
-</tr>
 <tr>
        <td>open</td>
        <td>/sessions/login</td>
 <tr>
        <td>type</td>
        <td>password</td>
-       <td>root-user</td>
+       <td>admin2</td>
 </tr>
 <tr>
        <td>type</td>
        <td>login</td>
-       <td>root-user</td>
+       <td>admin2</td>
 </tr>
 <tr>
        <td>clickAndWait</td>
index d770d855393504b17803b4739f8ecf6706eac20f..c267bf702e3fcee6a4405c2f3680a1cd5cbada3c 100644 (file)
 </tr>
 </thead>
 <tbody>
-<tr>
-       <td>open</td>
-       <td>/sessions/logout</td>
-       <td></td>
-</tr>
 <tr>
        <td>open</td>
        <td>/sessions/login</td>
 <tr>
        <td>type</td>
        <td>password</td>
-       <td>root-user</td>
+       <td>admin2</td>
 </tr>
 <tr>
        <td>type</td>
        <td>login</td>
-       <td>root-user</td>
+       <td>admin2</td>
 </tr>
 <tr>
        <td>clickAndWait</td>
index ada80dbf6b367cca8bf89e8c137be6764cf30bc3..d2f0a12a8b3d327d026d4bb351fe998727973d30 100644 (file)
 </tr>
 </thead>
 <tbody>
-<tr>
-       <td>open</td>
-       <td>/sessions/logout</td>
-       <td></td>
-</tr>
 <tr>
        <td>open</td>
        <td>/sessions/login</td>
index 61c550aec535ef22f25dfe41326eecb7381407ae..7fefabfbd4a3532607414aeae74677eae5f93cb2 100644 (file)
@@ -8,17 +8,7 @@
 </head>
 <body>
 <table cellpadding="1" cellspacing="1" border="1">
-<thead>
-<tr>
-<td rowspan="1" colspan="3">should_create</td>
-</tr>
-</thead>
 <tbody>
-<tr>
-       <td>open</td>
-       <td>/sessions/logout</td>
-       <td></td>
-</tr>
 <tr>
        <td>open</td>
        <td>/sessions/login</td>
index 6574ed04017c0139a9e365db34513cc99c3542cc..85e85c0391cc9fc08b1d534119ebc92cff28751e 100644 (file)
@@ -8,17 +8,7 @@
 </head>
 <body>
 <table cellpadding="1" cellspacing="1" border="1">
-<thead>
-<tr>
-<td rowspan="1" colspan="3">should_create</td>
-</tr>
-</thead>
 <tbody>
-<tr>
-       <td>open</td>
-       <td>/sessions/logout</td>
-       <td></td>
-</tr>
 <tr>
        <td>open</td>
        <td>/sessions/login</td>
index 609e4871865445da23795d5ec08589df87049c34..dfa3138f8b1789b15b41bd81d1039d334391aef7 100644 (file)
 </tr>
 </thead>
 <tbody>
-<tr>
-       <td>open</td>
-       <td>/sessions/logout</td>
-       <td></td>
-</tr>
 <tr>
        <td>open</td>
        <td>/sessions/login</td>
index a1d952d31dccf7d3e02bcaf167311d7a5bb78ce4..8def772700158cdd750da843ff10e826fc32e5b5 100644 (file)
@@ -8,17 +8,7 @@
 </head>
 <body>
 <table cellpadding="1" cellspacing="1" border="1">
-<thead>
-<tr>
-<td rowspan="1" colspan="3">should_create</td>
-</tr>
-</thead>
 <tbody>
-<tr>
-       <td>open</td>
-       <td>/sessions/logout</td>
-       <td></td>
-</tr>
 <tr>
        <td>open</td>
        <td>/sessions/login</td>
index 1a6425b6462797fffa44e0037c73287f8110bb40..6306820ba6add19fec6a1e5f460429b1943b3e48 100644 (file)
@@ -8,17 +8,7 @@
 </head>
 <body>
 <table cellpadding="1" cellspacing="1" border="1">
-<thead>
-<tr>
-<td rowspan="1" colspan="3">should_create</td>
-</tr>
-</thead>
 <tbody>
-<tr>
-       <td>open</td>
-       <td>/sessions/logout</td>
-       <td></td>
-</tr>
 <tr>
        <td>open</td>
        <td>/sessions/login</td>
index 7633c5cf7fc31ca5f5cac2992e60166fb057bb14..3560fb98efbe5517e2e6d340fe004e515bf09018 100644 (file)
@@ -180,12 +180,12 @@ class DefaultWsClient implements WsClient {
   }
 
   @Override
-  public SettingsService settingsService() {
+  public SettingsService settings() {
     return settingsService;
   }
 
   @Override
-  public RootsService rootService() {
+  public RootsService roots() {
     return rootsService;
   }
 
@@ -195,7 +195,7 @@ class DefaultWsClient implements WsClient {
   }
 
   @Override
-  public ProjectAnalysisService projectAnanlysis() {
+  public ProjectAnalysisService projectAnalysis() {
     return projectAnalysisService;
   }
 }
index 93062a58e4a6bbad9483485dd4646cc2dd3b1fdc..ec9ba3ef6d05aeaaa265ad5bab08125c1f58fa3d 100644 (file)
@@ -102,12 +102,12 @@ public interface WsClient {
   /**
    * @since 6.1
    */
-  SettingsService settingsService();
+  SettingsService settings();
 
   /**
    * @since 6.2
    */
-  RootsService rootService();
+  RootsService roots();
 
   /**
    * @since 6.2
@@ -117,5 +117,5 @@ public interface WsClient {
   /**
    * @since 6.3
    */
-  ProjectAnalysisService projectAnanlysis();
+  ProjectAnalysisService projectAnalysis();
 }
index edede842c06deff4e0d4ead57e18586cc5d3b343..7ef6337f055aba305725aa81ad1fa8e5770745f7 100644 (file)
@@ -19,7 +19,6 @@
  */
 package org.sonarqube.ws.client.organization;
 
-import javax.annotation.Nullable;
 import org.sonarqube.ws.Organizations.AddMemberWsResponse;
 import org.sonarqube.ws.Organizations.SearchMembersWsResponse;
 import org.sonarqube.ws.Organizations.SearchWsResponse;
@@ -72,7 +71,7 @@ public class OrganizationService extends BaseService {
     return call(post, UpdateWsResponse.parser());
   }
 
-  public void delete(@Nullable String key) {
+  public void delete(String key) {
     PostRequest post = new PostRequest(path("delete"))
       .setParam("organization", key);
 
index 4ad8ec57ea531717a3d4cf75982892a8bef76713..1f3cc16fc9bd70cbaf88194c73a5b009b967b83d 100644 (file)
@@ -28,6 +28,7 @@ public class ChangeParentRequest {
   private final String parentName;
   private final String profileKey;
   private final String profileName;
+  private final String organization;
 
   public ChangeParentRequest(Builder builder) {
     this.language = builder.language;
@@ -35,6 +36,7 @@ public class ChangeParentRequest {
     this.parentName = builder.parentName;
     this.profileKey = builder.profileKey;
     this.profileName = builder.profileName;
+    this.organization = builder.organization;
   }
 
   public String getLanguage() {
@@ -57,6 +59,10 @@ public class ChangeParentRequest {
     return profileName;
   }
 
+  public String getOrganization() {
+    return organization;
+  }
+
   public static Builder builder() {
     return new Builder();
   }
@@ -67,6 +73,7 @@ public class ChangeParentRequest {
     private String parentName;
     private String profileKey;
     private String profileName;
+    private String organization;
 
     private Builder() {
       // enforce factory method use
@@ -97,6 +104,11 @@ public class ChangeParentRequest {
       return this;
     }
 
+    public Builder setOrganization(@Nullable String s) {
+      this.organization = s;
+      return this;
+    }
+
     public ChangeParentRequest build() {
       return new ChangeParentRequest(this);
     }
diff --git a/sonar-ws/src/main/java/org/sonarqube/ws/client/qualityprofile/DeleteRequest.java b/sonar-ws/src/main/java/org/sonarqube/ws/client/qualityprofile/DeleteRequest.java
deleted file mode 100644 (file)
index 3eaa8e2..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * SonarQube
- * Copyright (C) 2009-2017 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.sonarqube.ws.client.qualityprofile;
-
-public class DeleteRequest {
-  private final String profileKey;
-
-  public DeleteRequest(String profileKey) {
-    this.profileKey = profileKey;
-  }
-
-  public String getProfileKey() {
-    return profileKey;
-  }
-}
index e885f51f1010638078620ee0c4f6bf47afdd966c..c3a6d02a925b530248e071eeb5185ef6875c78fc 100644 (file)
@@ -137,7 +137,8 @@ public class QualityProfilesService extends BaseService {
       .setParam(PARAM_PARENT_KEY, request.getParentKey())
       .setParam(PARAM_PARENT_NAME, request.getParentName())
       .setParam(PARAM_PROFILE_KEY, request.getProfileKey())
-      .setParam(PARAM_PROFILE_NAME, request.getProfileName()));
+      .setParam(PARAM_PROFILE_NAME, request.getProfileName())
+      .setParam(PARAM_ORGANIZATION, request.getOrganization()));
   }
 
   public void setDefault(SetDefaultRequest request) {
@@ -147,9 +148,9 @@ public class QualityProfilesService extends BaseService {
     call(postRequest);
   }
 
-  public void delete(DeleteRequest request) {
+  public void delete(String profileKey) {
     PostRequest postRequest = new PostRequest(path(ACTION_DELETE))
-      .setParam(PARAM_PROFILE_KEY, request.getProfileKey());
+      .setParam(PARAM_PROFILE_KEY, profileKey);
 
     call(postRequest);
   }
index 5c1da476c1a2883a4819b9b97d496eb0791a347c..c8151dc9133084efe0dbae54e80255e5455dc19a 100644 (file)
@@ -36,6 +36,7 @@ import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE;
 import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY;
 import static org.sonarqube.ws.client.user.UsersWsParameters.ACTION_CREATE;
 import static org.sonarqube.ws.client.user.UsersWsParameters.ACTION_CURRENT;
+import static org.sonarqube.ws.client.user.UsersWsParameters.ACTION_DEACTIVATE;
 import static org.sonarqube.ws.client.user.UsersWsParameters.ACTION_GROUPS;
 import static org.sonarqube.ws.client.user.UsersWsParameters.ACTION_SEARCH;
 import static org.sonarqube.ws.client.user.UsersWsParameters.ACTION_SKIP_ONBOARDING_TUTORIAL;
@@ -103,4 +104,10 @@ public class UsersService extends BaseService {
   public WsResponse skipOnboardingTutorial() {
     return call(new PostRequest(path(ACTION_SKIP_ONBOARDING_TUTORIAL)));
   }
+
+  public void deactivate(String login) {
+    call(new PostRequest(path(ACTION_DEACTIVATE))
+      .setParam(PARAM_LOGIN, login));
+  }
+
 }
index 2e648e047a57408938684a4a30556845b9411f15..cb0b3290bfb8c4634847552bb91f353d35f67a57 100644 (file)
@@ -25,6 +25,7 @@ public class UsersWsParameters {
 
   public static final String ACTION_SEARCH = "search";
   public static final String ACTION_CREATE = "create";
+  public static final String ACTION_DEACTIVATE = "deactivate";
   public static final String ACTION_UPDATE = "update";
   public static final String ACTION_GROUPS = "groups";
   public static final String ACTION_SKIP_ONBOARDING_TUTORIAL = "skip_onboarding_tutorial";
index ae1d3c9c0f38a10945f746a465124f4a632e9dc6..60052f0b4b46cfbbd016a2357492f5a48e8a0f08 100644 (file)
@@ -132,7 +132,7 @@ public class QualityProfilesServiceTest {
 
   @Test
   public void delete() {
-    underTest.delete(new DeleteRequest("sample"));
+    underTest.delete("sample");
 
     serviceTester.assertThat(serviceTester.getPostRequest())
       .hasPath("delete")