./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"
;;
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;
// user
MyAccountPageTest.class,
FavoritesWsTest.class,
- OnboardingTest.class,
// authentication
ForceAuthenticationTest.class,
LocalAuthenticationTest.class,
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;
// update center
UpdateCenterTest.class,
RealmAuthenticationTest.class,
- SsoAuthenticationTest.class
+ SsoAuthenticationTest.class,
+ OnboardingTest.class
})
public class Category5Suite {
@Rule
public UserRule userRule = UserRule.from(orchestrator);
- @Rule
- public Navigation nav = Navigation.get(orchestrator);
+ private Navigation nav = Navigation.create(orchestrator);
private String adminUser;
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)
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;
@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())
.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"};
// 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())
@Rule
public UserRule userRule = UserRule.from(ORCHESTRATOR);
- @Rule
- public Navigation nav = Navigation.get(ORCHESTRATOR);
+ public Navigation nav = Navigation.create(ORCHESTRATOR);
private String adminUser;
@Test
public void should_not_display_actions() {
+ Navigation nav = Navigation.create(ORCHESTRATOR);
IssuesPage page = nav.openIssues();
Issue issue = page.getFirstIssue();
issue.shouldNotAllowAssign().shouldNotAllowChangeType();
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) {
}
private void provisionProject(String projectKey, String organization) {
- adminClient.projects().create(
+ tester.wsClient().projects().create(
CreateRequest.builder()
.setKey(projectKey)
.setName(projectKey)
}
private void addQualityProfileToProject(String organization, String projectKey) {
- adminClient.qualityProfiles().addProject(
+ tester.wsClient().qualityProfiles().addProject(
AddProjectRequest.builder()
.setProjectKey(projectKey)
.setOrganization(organization)
.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()));
+ }
}
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;
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);
@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")));
@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;
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"));
.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();
@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
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
@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);
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");
}
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;
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
}
@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);
}
}
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");
}
@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");
@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());
}
}
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);
@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);
@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()
@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)
.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);
}
}
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;
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);
@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)
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")
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("")
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())
// 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();
@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",
@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");
}
@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);
@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) {
}
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());
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 -> {
} 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());
}
}
private void assertThatQualityProfilesDoNotExist(Organization org) {
- expectNotFoundError(() -> adminClient.qualityProfiles().search(
+ expectNotFoundError(() -> tester.wsClient().qualityProfiles().search(
new org.sonarqube.ws.client.qualityprofile.SearchWsRequest().setOrganizationKey(org.getKey())));
}
}
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;
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);
}
}
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());
}
}
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());
}
}
@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() {
@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);
@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";
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;
@ClassRule
public static Orchestrator ORCHESTRATOR = Category1Suite.ORCHESTRATOR;
- @Rule
- public Navigation nav = Navigation.get(ORCHESTRATOR);
-
private static WsClient wsClient;
@BeforeClass
ORCHESTRATOR.resetData();
}
+ private Navigation nav = Navigation.create(ORCHESTRATOR);
+
@Test
public void change_key_when_no_modules() {
createProject("sample");
@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);
@Rule
public UserRule userRule = UserRule.from(orchestrator);
- @Rule
- public Navigation nav = Navigation.get(orchestrator);
+ private Navigation nav = Navigation.create(orchestrator);
private String adminUser;
@BeforeClass
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;
@ClassRule
public static Orchestrator ORCHESTRATOR = Category1Suite.ORCHESTRATOR;
- @Rule
- public Navigation nav = Navigation.get(ORCHESTRATOR);
+ private Navigation nav = Navigation.create(ORCHESTRATOR);
private static WsClient wsClient;
@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 {
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;
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;
@Before
public void setUp() {
- organization = organizationRule.create();
+ organization = tester.organizations().generate();
restoreProfile(orchestrator, SearchProjectsTest.class.getResource("/projectSearch/SearchProjectsTest/with-many-rules.xml"), organization.getKey());
}
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);
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")
@Test
public void should_display_facets() {
- ProjectsPage page = nav.openProjects();
+ ProjectsPage page = tester.openBrowser().openProjects();
page.getFacetByProperty("duplications")
.shouldHaveValue("1", "1")
.shouldHaveValue("2", "1")
@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);
@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();
@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");
@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")
@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");
@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();
@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);
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;
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());
}
@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());
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());
}
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 {
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");
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;
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)
@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)
@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());
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()));
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()));
}
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)
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;
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;
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());
@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()));
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()));
@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)
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",
@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);
}
@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()));
- }
-
}
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 {
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 {
}
@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",
@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);
}
@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));
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;
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
}
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();
}
}
}
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;
@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()
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");
}
@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();
@Rule
public UserRule userRule = UserRule.from(orchestrator);
- @Rule
- public Navigation nav = Navigation.get(orchestrator);
private String adminUser;
@BeforeClass
@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"));
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);
}
@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
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
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")
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");
import it.Category4Suite;
import org.junit.BeforeClass;
import org.junit.ClassRule;
-import org.junit.Rule;
import org.junit.Test;
import pageobjects.Navigation;
@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() {
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;
@ClassRule
public static final Orchestrator ORCHESTRATOR = Category4Suite.ORCHESTRATOR;
- @Rule
- public Navigation nav = Navigation.get(ORCHESTRATOR);
+ private Navigation nav = Navigation.create(ORCHESTRATOR);
@Before
@After
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.$;
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();
@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();
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 {
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();
}
@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();
}
@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();
}
@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();
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();
+ }
}
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);
}
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);
}
@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);
}
}
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;
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;
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();
@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();
}
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}");
}
@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);
}
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();
@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",
// 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");
}
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();
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);
}
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));
}
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;
@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"));
@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");
@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");
.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)
.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)
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)
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;
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 {
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",
}
@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
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
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
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);
}
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();
}
}
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
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();
- }
-
}
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) {
}
}
- private static void authenticateWithFakeAuthProvider() {
- adminWsClient.wsConnector().call(
+ private void authenticateWithFakeAuthProvider() {
+ tester.wsClient().wsConnector().call(
new GetRequest("/sessions/init/fake-base-id-provider"))
.failIfNotSuccessful();
}
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);
}
}
--- /dev/null
+/*
+ * 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;
+ }
+}
--- /dev/null
+/*
+ * 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();
+ }
+}
--- /dev/null
+/*
+ * 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;
+ }
+}
--- /dev/null
+/*
+ * 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();
+
+}
--- /dev/null
+/*
+ * 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);
+ }
+ }
+}
--- /dev/null
+/*
+ * 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();
+ }
+}
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);
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);
}
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() {
return $(".js-user-authenticated");
}
- public void shouldBeRedirectToLogin() {
- $("#content").should(hasText("Log In to SonarQube"));
+ public Navigation shouldBeRedirectedToLogin() {
+ $("#login_form").should(visible);
+ return this;
}
}
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";
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);
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());
}
}
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());
}
}
}
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");
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);
+ }
+ }
}
+++ /dev/null
-/*
- * 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;
- }
- }
-}
+++ /dev/null
-/*
- * 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);
-
-}
+++ /dev/null
-/*
- * 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;
- }
-
- }
-}
+++ /dev/null
-/*
- * 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);
- }
-}
}
/**
- * 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();
}
}
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;
}
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) {
</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>
</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>
</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>
</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>
</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>
</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>
</tr>
</thead>
<tbody>
-<tr>
- <td>open</td>
- <td>/sessions/logout</td>
- <td></td>
-</tr>
<tr>
<td>open</td>
<td>/sessions/login</td>
</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>
</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>
</tr>
</thead>
<tbody>
-<tr>
- <td>open</td>
- <td>/sessions/logout</td>
- <td></td>
-</tr>
<tr>
<td>open</td>
<td>/sessions/login</td>
</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>
</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>
}
@Override
- public SettingsService settingsService() {
+ public SettingsService settings() {
return settingsService;
}
@Override
- public RootsService rootService() {
+ public RootsService roots() {
return rootsService;
}
}
@Override
- public ProjectAnalysisService projectAnanlysis() {
+ public ProjectAnalysisService projectAnalysis() {
return projectAnalysisService;
}
}
/**
* @since 6.1
*/
- SettingsService settingsService();
+ SettingsService settings();
/**
* @since 6.2
*/
- RootsService rootService();
+ RootsService roots();
/**
* @since 6.2
/**
* @since 6.3
*/
- ProjectAnalysisService projectAnanlysis();
+ ProjectAnalysisService projectAnalysis();
}
*/
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;
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);
private final String parentName;
private final String profileKey;
private final String profileName;
+ private final String organization;
public ChangeParentRequest(Builder builder) {
this.language = builder.language;
this.parentName = builder.parentName;
this.profileKey = builder.profileKey;
this.profileName = builder.profileName;
+ this.organization = builder.organization;
}
public String getLanguage() {
return profileName;
}
+ public String getOrganization() {
+ return organization;
+ }
+
public static Builder builder() {
return new Builder();
}
private String parentName;
private String profileKey;
private String profileName;
+ private String organization;
private Builder() {
// enforce factory method use
return this;
}
+ public Builder setOrganization(@Nullable String s) {
+ this.organization = s;
+ return this;
+ }
+
public ChangeParentRequest build() {
return new ChangeParentRequest(this);
}
+++ /dev/null
-/*
- * 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;
- }
-}
.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) {
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);
}
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;
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));
+ }
+
}
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";
@Test
public void delete() {
- underTest.delete(new DeleteRequest("sample"));
+ underTest.delete("sample");
serviceTester.assertThat(serviceTester.getPostRequest())
.hasPath("delete")