]> source.dussan.org Git - sonarqube.git/commitdiff
SONAR-13999 drop organization from CE WS
authorJacek <jacek.poreda@sonarsource.com>
Tue, 8 Dec 2020 16:02:46 +0000 (17:02 +0100)
committersonartech <sonartech@sonarsource.com>
Tue, 22 Dec 2020 20:09:35 +0000 (20:09 +0000)
22 files changed:
server/sonar-db-dao/src/main/java/org/sonar/db/organization/OrganizationDao.java
server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ComponentDbTester.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/queue/BranchSupport.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/queue/BranchSupportDelegate.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/queue/ReportSubmitter.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/AnalysisStatusAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/SubmitAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/TaskFormatter.java
server/sonar-webserver-webapi/src/main/resources/org/sonar/server/ce/ws/analysis_status-example.json
server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/queue/BranchReportSubmitterTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/queue/BranchSupportTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/queue/CeQueueCleanerTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/queue/ReportSubmitterTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/ActivityActionTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/ActivityStatusActionTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/AnalysisStatusActionTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/CeWsTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/ComponentActionTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/SubmitActionTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/TaskActionTest.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/TaskFormatterTest.java
sonar-ws/src/main/protobuf/ws-ce.proto

index f120445e3bfb2852d2fecc28daa0b151db2aa4ea..d1453a5d32c103487a9f6d1d74b2a080aa2f2707 100644 (file)
@@ -123,6 +123,10 @@ public class OrganizationDao implements Dao {
     getMapper(dbSession).updateDefaultQualityGate(organization.getUuid(), qualityGate.getUuid(), system2.now());
   }
 
+  public boolean getNewProjectPrivate(DbSession dbSession, String organizationUuid) {
+    return getMapper(dbSession).selectNewProjectPrivateByUuid(organizationUuid);
+  }
+
   public boolean getNewProjectPrivate(DbSession dbSession, OrganizationDto organization) {
     return getMapper(dbSession).selectNewProjectPrivateByUuid(organization.getUuid());
   }
index d617b3cddaaa68be1608343a80adb22733a32541..03954390f6476c94a0b4003cdcf9e9398f9875a4 100644 (file)
@@ -247,6 +247,10 @@ public class ComponentDbTester {
     return insertComponentImpl(ComponentTesting.newView(organizationDto, uuid), false, defaults());
   }
 
+  public final ComponentDto insertPublicPortfolio() {
+    return insertPublicPortfolio(db.getDefaultOrganization(), defaults());
+  }
+
   public final ComponentDto insertPublicPortfolio(OrganizationDto organization) {
     return insertPublicPortfolio(organization, defaults());
   }
index 86dcd80d5801b024589b6631c3725ffa559042f5..bab70e123b2dca19d65e62284427bde33c12dd13 100644 (file)
@@ -28,7 +28,6 @@ import org.sonar.api.server.ServerSide;
 import org.sonar.db.DbSession;
 import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.ComponentDto;
-import org.sonar.db.organization.OrganizationDto;
 
 import static com.google.common.base.Preconditions.checkState;
 
@@ -63,11 +62,11 @@ public class BranchSupport {
     return delegate.createComponentKey(projectKey, characteristics);
   }
 
-  ComponentDto createBranchComponent(DbSession dbSession, ComponentKey componentKey, OrganizationDto organization,
+  ComponentDto createBranchComponent(DbSession dbSession, ComponentKey componentKey,
     ComponentDto mainComponentDto, BranchDto mainComponentBranchDto) {
     checkState(delegate != null, "Current edition does not support branch feature");
 
-    return delegate.createBranchComponent(dbSession, componentKey, organization, mainComponentDto, mainComponentBranchDto);
+    return delegate.createBranchComponent(dbSession, componentKey, mainComponentDto, mainComponentBranchDto);
   }
 
   public abstract static class ComponentKey {
@@ -89,7 +88,6 @@ public class BranchSupport {
     public abstract ComponentKey getMainBranchComponentKey();
   }
 
-
   private static final class ComponentKeyImpl extends ComponentKey {
     private final String key;
     private final String dbKey;
index 328668f02ada7b8b321dd0b451286a0b0da2717e..f7734a5643d3bb49670be400484c7410c4417b5b 100644 (file)
@@ -25,7 +25,6 @@ import org.sonar.db.DbSession;
 import org.sonar.db.ce.CeTaskCharacteristicDto;
 import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.ComponentDto;
-import org.sonar.db.organization.OrganizationDto;
 import org.sonar.server.ce.queue.BranchSupport.ComponentKey;
 
 @ServerSide
@@ -46,11 +45,11 @@ public interface BranchSupportDelegate {
 
   /**
    * Creates the ComponentDto for the branch described in {@code componentKey} which belongs to the specified
-   * {@code mainComponentDto} in the specified {@code organization}.
+   * {@code mainComponentDto}
    *
    * @throws IllegalArgumentException if arguments are inconsistent (such as {@code mainComponentDto} not having the same
    *         key as {@code componentKey.getKey()}, ...)
    */
-  ComponentDto createBranchComponent(DbSession dbSession, ComponentKey componentKey,
-    OrganizationDto organization, ComponentDto mainComponentDto, BranchDto mainComponentBranchDto);
+  ComponentDto createBranchComponent(DbSession dbSession, ComponentKey componentKey, ComponentDto mainComponentDto,
+    BranchDto mainComponentBranchDto);
 }
index c62ccfd780511f29f63c4f38d7809bbbe1c99a1f..24dacf4411e1337f2ef84122f2cb50ab6f03dfea 100644 (file)
@@ -37,16 +37,15 @@ import org.sonar.db.DbSession;
 import org.sonar.db.ce.CeTaskTypes;
 import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.ComponentDto;
-import org.sonar.db.organization.OrganizationDto;
 import org.sonar.db.permission.GlobalPermission;
 import org.sonar.server.component.ComponentUpdater;
 import org.sonar.server.component.NewComponent;
 import org.sonar.server.exceptions.BadRequestException;
 import org.sonar.server.exceptions.NotFoundException;
+import org.sonar.server.organization.DefaultOrganizationProvider;
 import org.sonar.server.permission.PermissionTemplateService;
 import org.sonar.server.user.UserSession;
 
-import static com.google.common.base.Preconditions.checkArgument;
 import static java.lang.String.format;
 import static org.apache.commons.lang.StringUtils.defaultIfBlank;
 import static org.sonar.server.component.NewComponent.newComponentBuilder;
@@ -61,26 +60,25 @@ public class ReportSubmitter {
   private final PermissionTemplateService permissionTemplateService;
   private final DbClient dbClient;
   private final BranchSupport branchSupport;
+  private final DefaultOrganizationProvider defaultOrganizationProvider;
 
   public ReportSubmitter(CeQueue queue, UserSession userSession, ComponentUpdater componentUpdater,
-    PermissionTemplateService permissionTemplateService, DbClient dbClient, BranchSupport branchSupport) {
+    PermissionTemplateService permissionTemplateService, DbClient dbClient, BranchSupport branchSupport,
+    DefaultOrganizationProvider defaultOrganizationProvider) {
     this.queue = queue;
     this.userSession = userSession;
     this.componentUpdater = componentUpdater;
     this.permissionTemplateService = permissionTemplateService;
     this.dbClient = dbClient;
     this.branchSupport = branchSupport;
+    this.defaultOrganizationProvider = defaultOrganizationProvider;
   }
 
-  /**
-   * @throws NotFoundException if the organization with the specified key does not exist
-   * @throws IllegalArgumentException if the organization with the specified key is not the organization of the specified project (when it already exists in DB)
-   */
-  public CeTask submit(String organizationKey, String projectKey, @Nullable String projectName, Map<String, String> characteristics, InputStream reportInput) {
+  public CeTask submit(String projectKey, @Nullable String projectName, Map<String, String> characteristics, InputStream reportInput) {
     try (DbSession dbSession = dbClient.openSession(false)) {
       boolean projectCreated = false;
-      OrganizationDto organizationDto = getOrganizationDtoOrFail(dbSession, organizationKey);
-      // Note: when the main branch is analyzed, the characteristics may or may not have the branch name, so componentKey#isMainBranch is not reliable!
+      // Note: when the main branch is analyzed, the characteristics may or may not have the branch name, so componentKey#isMainBranch is not
+      // reliable!
       BranchSupport.ComponentKey componentKey = branchSupport.createComponentKey(projectKey, characteristics);
       Optional<ComponentDto> mainBranchComponentOpt = dbClient.componentDao().selectByKey(dbSession, componentKey.getKey());
       ComponentDto mainBranchComponent;
@@ -88,9 +86,8 @@ public class ReportSubmitter {
       if (mainBranchComponentOpt.isPresent()) {
         mainBranchComponent = mainBranchComponentOpt.get();
         validateProject(dbSession, mainBranchComponent, projectKey);
-        ensureOrganizationIsConsistent(mainBranchComponent, organizationDto);
       } else {
-        mainBranchComponent = createProject(dbSession, organizationDto, componentKey.getMainBranchComponentKey(), projectName);
+        mainBranchComponent = createProject(dbSession, componentKey.getMainBranchComponentKey(), projectName);
         projectCreated = true;
       }
 
@@ -101,7 +98,7 @@ public class ReportSubmitter {
         branchComponent = mainBranchComponent;
       } else {
         branchComponent = dbClient.componentDao().selectByKey(dbSession, componentKey.getDbKey())
-          .orElseGet(() -> branchSupport.createBranchComponent(dbSession, componentKey, organizationDto, mainBranchComponent, mainBranch));
+          .orElseGet(() -> branchSupport.createBranchComponent(dbSession, componentKey, mainBranchComponent, mainBranch));
       }
 
       if (projectCreated) {
@@ -134,11 +131,6 @@ public class ReportSubmitter {
     }
   }
 
-  private OrganizationDto getOrganizationDtoOrFail(DbSession dbSession, String organizationKey) {
-    return dbClient.organizationDao().selectByKey(dbSession, organizationKey)
-      .orElseThrow(() -> new NotFoundException(format("Organization with key '%s' does not exist", organizationKey)));
-  }
-
   private void validateProject(DbSession dbSession, ComponentDto component, String rawProjectKey) {
     List<String> errors = new ArrayList<>();
 
@@ -149,7 +141,7 @@ public class ReportSubmitter {
       // Project key is already used as a module of another project
       ComponentDto anotherBaseProject = dbClient.componentDao().selectOrFailByUuid(dbSession, component.projectUuid());
       errors.add(format("The project '%s' is already defined in SonarQube but as a module of project '%s'. "
-          + "If you really want to stop directly analysing project '%s', please first delete it from SonarQube and then relaunch the analysis of project '%s'.",
+        + "If you really want to stop directly analysing project '%s', please first delete it from SonarQube and then relaunch the analysis of project '%s'.",
         rawProjectKey, anotherBaseProject.getKey(), anotherBaseProject.getKey(), rawProjectKey));
     }
     if (!errors.isEmpty()) {
@@ -157,13 +149,7 @@ public class ReportSubmitter {
     }
   }
 
-  private static void ensureOrganizationIsConsistent(ComponentDto project, OrganizationDto organizationDto) {
-    checkArgument(project.getOrganizationUuid().equals(organizationDto.getUuid()),
-      "Organization of component with key '%s' does not match specified organization '%s'",
-      project.getDbKey(), organizationDto.getKey());
-  }
-
-  private ComponentDto createProject(DbSession dbSession, OrganizationDto organization, BranchSupport.ComponentKey componentKey, @Nullable String projectName) {
+  private ComponentDto createProject(DbSession dbSession, BranchSupport.ComponentKey componentKey, @Nullable String projectName) {
     userSession.checkPermission(GlobalPermission.PROVISION_PROJECTS);
     String userUuid = userSession.getUuid();
 
@@ -173,10 +159,12 @@ public class ReportSubmitter {
       throw insufficientPrivilegesException();
     }
 
-    boolean newProjectPrivate = dbClient.organizationDao().getNewProjectPrivate(dbSession, organization);
+    // TODO:: remove once we move organization settings somewhere else
+    String defaultOrgUuid = defaultOrganizationProvider.get().getUuid();
+    boolean newProjectPrivate = dbClient.organizationDao().getNewProjectPrivate(dbSession, defaultOrgUuid);
 
     NewComponent newProject = newComponentBuilder()
-      .setOrganizationUuid(organization.getUuid())
+      .setOrganizationUuid(defaultOrgUuid)
       .setKey(componentKey.getKey())
       .setName(defaultIfBlank(projectName, componentKey.getKey()))
       .setQualifier(Qualifiers.PROJECT)
index 5825ebbfcbc45f7fd042f8410630c711351693bd..72754923d27d880eab4a61aa2376bdd9dee1236e 100644 (file)
@@ -111,7 +111,6 @@ public class AnalysisStatusAction implements CeWsAction {
   private AnalysisStatusWsResponse.Component formatComponent(DbSession dbSession, ProjectDto project, @Nullable CeActivityDto lastActivity,
     @Nullable String branchKey, @Nullable String pullRequestKey) {
     AnalysisStatusWsResponse.Component.Builder builder = AnalysisStatusWsResponse.Component.newBuilder()
-      .setOrganization(getOrganizationKey(dbSession, project))
       .setKey(project.getKey())
       .setName(project.getName());
 
@@ -143,11 +142,4 @@ public class AnalysisStatusAction implements CeWsAction {
     return builder.build();
   }
 
-  private String getOrganizationKey(DbSession dbSession, ProjectDto project) {
-    String organizationUuid = project.getOrganizationUuid();
-    return dbClient.organizationDao().selectByUuid(dbSession, organizationUuid)
-      .orElseThrow(() -> new IllegalStateException("Unknown organization: " + organizationUuid))
-      .getKey();
-  }
-
 }
index ea9bb458cd7d3ebd0e7f64828d45bdafed8cd2f9..dc3d1bc296b72e1c113bcb35c1aa87af94c01126 100644 (file)
@@ -30,7 +30,6 @@ import org.sonar.api.server.ws.WebService;
 import org.sonar.ce.task.CeTask;
 import org.sonar.db.ce.CeTaskCharacteristicDto;
 import org.sonar.server.ce.queue.ReportSubmitter;
-import org.sonar.server.organization.DefaultOrganizationProvider;
 import org.sonar.server.ws.WsUtils;
 import org.sonarqube.ws.Ce;
 
@@ -42,18 +41,15 @@ import static org.sonar.server.exceptions.BadRequestException.checkRequest;
 
 public class SubmitAction implements CeWsAction {
 
-  private static final String PARAM_ORGANIZATION_KEY = "organization";
   private static final String PARAM_PROJECT_KEY = "projectKey";
   private static final String PARAM_PROJECT_NAME = "projectName";
   private static final String PARAM_REPORT_DATA = "report";
   private static final String PARAM_ANALYSIS_CHARACTERISTIC = "characteristic";
 
   private final ReportSubmitter reportSubmitter;
-  private final DefaultOrganizationProvider defaultOrganizationProvider;
 
-  public SubmitAction(ReportSubmitter reportSubmitter, DefaultOrganizationProvider defaultOrganizationProvider) {
+  public SubmitAction(ReportSubmitter reportSubmitter) {
     this.reportSubmitter = reportSubmitter;
-    this.defaultOrganizationProvider = defaultOrganizationProvider;
   }
 
   @Override
@@ -67,12 +63,6 @@ public class SubmitAction implements CeWsAction {
       .setHandler(this)
       .setResponseExample(getClass().getResource("submit-example.json"));
 
-    action.createParam(PARAM_ORGANIZATION_KEY)
-      .setDescription("Key of the organization the project belongs to")
-      .setExampleValue("my-org")
-      .setSince("6.3")
-      .setInternal(true);
-
     action
       .createParam(PARAM_PROJECT_KEY)
       .setRequired(true)
@@ -101,16 +91,13 @@ public class SubmitAction implements CeWsAction {
 
   @Override
   public void handle(Request wsRequest, Response wsResponse) throws Exception {
-    String organizationKey = wsRequest.getParam(PARAM_ORGANIZATION_KEY)
-      .emptyAsNull()
-      .or(defaultOrganizationProvider.get()::getKey);
     String projectKey = wsRequest.mandatoryParam(PARAM_PROJECT_KEY);
     String projectName = abbreviate(defaultIfBlank(wsRequest.param(PARAM_PROJECT_NAME), projectKey), MAX_COMPONENT_NAME_LENGTH);
 
     Map<String, String> characteristics = parseTaskCharacteristics(wsRequest);
 
     try (InputStream report = new BufferedInputStream(wsRequest.mandatoryParamAsPart(PARAM_REPORT_DATA).getInputStream())) {
-      CeTask task = reportSubmitter.submit(organizationKey, projectKey, projectName, characteristics, report);
+      CeTask task = reportSubmitter.submit(projectKey, projectName, characteristics, report);
       Ce.SubmitResponse submitResponse = Ce.SubmitResponse.newBuilder()
         .setTaskId(task.getUuid())
         .setProjectId(task.getComponent().get().getUuid())
index 2f0fe63d7f19f7fe05f318509e3adc175e1c7091..1a4623d2a323a84463186bf813dccf577084cf94 100644 (file)
@@ -39,12 +39,10 @@ import org.sonar.db.ce.CeActivityDto;
 import org.sonar.db.ce.CeQueueDto;
 import org.sonar.db.ce.CeTaskCharacteristicDto;
 import org.sonar.db.component.ComponentDto;
-import org.sonar.db.organization.OrganizationDto;
 import org.sonar.db.user.UserDto;
 import org.sonarqube.ws.Ce;
 import org.sonarqube.ws.Common;
 
-import static com.google.common.base.Preconditions.checkState;
 import static java.lang.String.format;
 import static java.util.Collections.emptyList;
 import static java.util.Collections.singletonList;
@@ -78,8 +76,6 @@ public class TaskFormatter {
 
   private Ce.Task formatQueue(CeQueueDto dto, DtoCache cache) {
     Ce.Task.Builder builder = Ce.Task.newBuilder();
-    String organizationKey = cache.getOrganizationKey(dto.getComponentUuid());
-    ofNullable(organizationKey).ifPresent(builder::setOrganization);
     if (dto.getComponentUuid() != null) {
       builder.setComponentId(dto.getComponentUuid());
       setComponent(builder, dto.getComponentUuid(), cache);
@@ -109,8 +105,6 @@ public class TaskFormatter {
 
   private static Ce.Task formatActivity(CeActivityDto dto, DtoCache cache, @Nullable String scannerContext, List<String> warnings) {
     Ce.Task.Builder builder = Ce.Task.newBuilder();
-    String organizationKey = cache.getOrganizationKey(dto.getComponentUuid());
-    ofNullable(organizationKey).ifPresent(builder::setOrganization);
     builder.setId(dto.getUuid());
     builder.setStatus(Ce.TaskStatus.valueOf(dto.getStatus().name()));
     builder.setType(dto.getTaskType());
@@ -167,14 +161,11 @@ public class TaskFormatter {
 
   private static class DtoCache {
     private final Map<String, ComponentDto> componentsByUuid;
-    private final Map<String, OrganizationDto> organizationsByUuid;
     private final Multimap<String, CeTaskCharacteristicDto> characteristicsByTaskUuid;
     private final Map<String, UserDto> usersByUuid;
 
-    private DtoCache(Map<String, ComponentDto> componentsByUuid, Map<String, OrganizationDto> organizationsByUuid,
-      Multimap<String, CeTaskCharacteristicDto> characteristicsByTaskUuid, Map<String, UserDto> usersByUuid) {
+    private DtoCache(Map<String, ComponentDto> componentsByUuid, Multimap<String, CeTaskCharacteristicDto> characteristicsByTaskUuid, Map<String, UserDto> usersByUuid) {
       this.componentsByUuid = componentsByUuid;
-      this.organizationsByUuid = organizationsByUuid;
       this.characteristicsByTaskUuid = characteristicsByTaskUuid;
       this.usersByUuid = usersByUuid;
     }
@@ -188,7 +179,7 @@ public class TaskFormatter {
         .stream().collect(MoreCollectors.index(CeTaskCharacteristicDto::getTaskUuid));
       Set<String> submitterUuids = ceQueueDtos.stream().map(CeQueueDto::getSubmitterUuid).filter(Objects::nonNull).collect(toSet());
       Map<String, UserDto> usersByUuid = dbClient.userDao().selectByUuids(dbSession, submitterUuids).stream().collect(uniqueIndex(UserDto::getUuid));
-      return new DtoCache(componentsByUuid, buildOrganizationsByUuid(dbClient, dbSession, componentsByUuid), characteristicsByTaskUuid, usersByUuid);
+      return new DtoCache(componentsByUuid, characteristicsByTaskUuid, usersByUuid);
     }
 
     private static Set<String> componentUuidsOfCeQueues(Collection<CeQueueDto> ceQueueDtos) {
@@ -210,7 +201,7 @@ public class TaskFormatter {
         .stream().collect(MoreCollectors.index(CeTaskCharacteristicDto::getTaskUuid));
       Set<String> submitterUuids = ceActivityDtos.stream().map(CeActivityDto::getSubmitterUuid).filter(Objects::nonNull).collect(toSet());
       Map<String, UserDto> usersByUuid = dbClient.userDao().selectByUuids(dbSession, submitterUuids).stream().collect(uniqueIndex(UserDto::getUuid));
-      return new DtoCache(componentsByUuid, buildOrganizationsByUuid(dbClient, dbSession, componentsByUuid), characteristicsByTaskUuid, usersByUuid);
+      return new DtoCache(componentsByUuid, characteristicsByTaskUuid, usersByUuid);
     }
 
     private static Set<String> getComponentUuidsOfCeActivities(Collection<CeActivityDto> ceActivityDtos) {
@@ -221,16 +212,6 @@ public class TaskFormatter {
         .collect(toSet(ceActivityDtos.size()));
     }
 
-    private static Map<String, OrganizationDto> buildOrganizationsByUuid(DbClient dbClient, DbSession dbSession, Map<String, ComponentDto> componentsByUuid) {
-      return dbClient.organizationDao().selectByUuids(
-        dbSession,
-        componentsByUuid.values().stream()
-          .map(ComponentDto::getOrganizationUuid)
-          .collect(toSet(componentsByUuid.size())))
-        .stream()
-        .collect(uniqueIndex(OrganizationDto::getUuid));
-    }
-
     @CheckForNull
     ComponentDto getComponent(@Nullable String uuid) {
       if (uuid == null) {
@@ -239,21 +220,6 @@ public class TaskFormatter {
       return componentsByUuid.get(uuid);
     }
 
-    @CheckForNull
-    String getOrganizationKey(@Nullable String componentUuid) {
-      if (componentUuid == null) {
-        return null;
-      }
-      ComponentDto componentDto = componentsByUuid.get(componentUuid);
-      if (componentDto == null) {
-        return null;
-      }
-      String organizationUuid = componentDto.getOrganizationUuid();
-      OrganizationDto organizationDto = organizationsByUuid.get(organizationUuid);
-      checkState(organizationDto != null, "Organization with uuid '%s' not found", organizationUuid);
-      return organizationDto.getKey();
-    }
-
     Optional<String> getBranchKey(String taskUuid) {
       return characteristicsByTaskUuid.get(taskUuid).stream()
         .filter(c -> c.getKey().equals(CeTaskCharacteristicDto.BRANCH_KEY))
index 791c38bb01853a2d52e891c40f6d8b4a2c20d278..c6402111ef48c1f2a58071ddfdcb38adfaf9919f 100644 (file)
@@ -1,6 +1,5 @@
 {
   "component": {
-    "organization": "my-org-1",
     "key": "com.github.kevinsawicki:http-request-parent",
     "name": "HttpRequest",
     "warnings": [
index deed7eb34fec132948da71ccdfb5f9972ecf29bf..830cc6a4926201b7acf04ed399c24f5345866ce8 100644 (file)
 package org.sonar.server.ce.queue;
 
 import com.google.common.collect.ImmutableMap;
-import com.tngtech.java.junit.dataprovider.DataProvider;
 import com.tngtech.java.junit.dataprovider.DataProviderRunner;
 import java.io.InputStream;
 import java.nio.charset.StandardCharsets;
 import java.util.Map;
 import java.util.Optional;
 import java.util.Random;
-import java.util.function.BiConsumer;
 import java.util.stream.IntStream;
 import org.apache.commons.io.IOUtils;
 import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 import org.junit.runner.RunWith;
 import org.mockito.stubbing.Answer;
 import org.sonar.api.utils.System2;
@@ -46,17 +43,19 @@ import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.BranchType;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.component.ComponentTesting;
-import org.sonar.db.organization.OrganizationDto;
 import org.sonar.db.user.UserDto;
 import org.sonar.server.component.ComponentUpdater;
 import org.sonar.server.exceptions.ForbiddenException;
 import org.sonar.server.favorite.FavoriteUpdater;
+import org.sonar.server.organization.DefaultOrganizationProvider;
+import org.sonar.server.organization.TestDefaultOrganizationProvider;
 import org.sonar.server.permission.PermissionTemplateService;
 import org.sonar.server.tester.UserSessionRule;
 
 import static java.util.Collections.emptyMap;
 import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.junit.Assert.fail;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.argThat;
@@ -69,7 +68,6 @@ import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.verifyNoInteractions;
 import static org.mockito.Mockito.verifyNoMoreInteractions;
 import static org.mockito.Mockito.when;
-import static org.sonar.core.permission.GlobalPermissions.PROVISIONING;
 import static org.sonar.core.permission.GlobalPermissions.SCAN_EXECUTION;
 import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
 import static org.sonar.db.component.ComponentTesting.newBranchDto;
@@ -84,39 +82,38 @@ import static org.sonar.db.permission.GlobalPermission.SCAN;
 public class BranchReportSubmitterTest {
 
   @Rule
-  public ExpectedException expectedException = ExpectedException.none();
+  public final UserSessionRule userSession = UserSessionRule.standalone();
   @Rule
-  public UserSessionRule userSession = UserSessionRule.standalone();
-  @Rule
-  public DbTester db = DbTester.create(System2.INSTANCE);
+  public final DbTester db = DbTester.create(System2.INSTANCE);
+
+  private final DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db);
 
-  private CeQueue queue = mock(CeQueueImpl.class);
-  private ComponentUpdater componentUpdater = mock(ComponentUpdater.class);
-  private PermissionTemplateService permissionTemplateService = mock(PermissionTemplateService.class);
-  private FavoriteUpdater favoriteUpdater = mock(FavoriteUpdater.class);
-  private BranchSupportDelegate branchSupportDelegate = mock(BranchSupportDelegate.class);
-  private BranchSupport branchSupport = spy(new BranchSupport(branchSupportDelegate));
+  private final CeQueue queue = mock(CeQueueImpl.class);
+  private final ComponentUpdater componentUpdater = mock(ComponentUpdater.class);
+  private final PermissionTemplateService permissionTemplateService = mock(PermissionTemplateService.class);
+  private final FavoriteUpdater favoriteUpdater = mock(FavoriteUpdater.class);
+  private final BranchSupportDelegate branchSupportDelegate = mock(BranchSupportDelegate.class);
+  private final BranchSupport branchSupport = spy(new BranchSupport(branchSupportDelegate));
 
-  private ReportSubmitter underTest = new ReportSubmitter(queue, userSession, componentUpdater, permissionTemplateService, db.getDbClient(), branchSupport);
+  private final ReportSubmitter underTest = new ReportSubmitter(queue, userSession, componentUpdater, permissionTemplateService, db.getDbClient(), branchSupport,
+    defaultOrganizationProvider);
 
   @Test
   public void submit_does_not_use_delegate_if_characteristics_are_empty() {
-    OrganizationDto organization = db.organizations().insert();
-    ComponentDto project = db.components().insertPublicProject(organization);
+    ComponentDto project = db.components().insertPublicProject();
     UserDto user = db.users().insertUser();
     userSession.logIn(user).addProjectPermission(SCAN_EXECUTION, project);
     mockSuccessfulPrepareSubmitCall();
     InputStream reportInput = IOUtils.toInputStream("{binary}", StandardCharsets.UTF_8);
 
-    underTest.submit(organization.getKey(), project.getDbKey(), project.name(), emptyMap(), reportInput);
+    underTest.submit(project.getDbKey(), project.name(), emptyMap(), reportInput);
 
     verifyNoInteractions(branchSupportDelegate);
   }
 
   @Test
   public void submit_a_report_on_existing_branch() {
-    OrganizationDto organization = db.organizations().insert();
-    ComponentDto project = db.components().insertPublicProject(organization);
+    ComponentDto project = db.components().insertPublicProject();
     ComponentDto branch = db.components().insertProjectBranch(project);
     UserDto user = db.users().insertUser();
     userSession.logIn(user).addProjectPermission(SCAN_EXECUTION, project);
@@ -127,21 +124,20 @@ public class BranchReportSubmitterTest {
     InputStream reportInput = IOUtils.toInputStream("{binary}", StandardCharsets.UTF_8);
     String taskUuid = mockSuccessfulPrepareSubmitCall();
 
-    underTest.submit(organization.getKey(), project.getDbKey(), project.name(), randomCharacteristics, reportInput);
+    underTest.submit(project.getDbKey(), project.name(), randomCharacteristics, reportInput);
 
     verifyNoInteractions(permissionTemplateService);
     verifyNoInteractions(favoriteUpdater);
-    verify(branchSupport, times(0)).createBranchComponent(any(), any(), any(), any(), any());
+    verify(branchSupport, times(0)).createBranchComponent(any(), any(), any(), any());
     verify(branchSupportDelegate).createComponentKey(project.getDbKey(), randomCharacteristics);
-    verify(branchSupportDelegate, times(0)).createBranchComponent(any(), any(), any(), any(), any());
+    verify(branchSupportDelegate, times(0)).createBranchComponent(any(), any(), any(), any());
     verifyNoMoreInteractions(branchSupportDelegate);
     verifyQueueSubmit(project, branch, user, randomCharacteristics, taskUuid);
   }
 
   @Test
   public void submit_a_report_on_missing_branch_but_existing_project() {
-    OrganizationDto organization = db.organizations().insert();
-    ComponentDto existingProject = db.components().insertPublicProject(organization);
+    ComponentDto existingProject = db.components().insertPublicProject();
     BranchDto exitingProjectMainBranch = db.getDbClient().branchDao().selectByUuid(db.getSession(), existingProject.uuid()).get();
     UserDto user = db.users().insertUser();
     userSession.logIn(user).addProjectPermission(SCAN_EXECUTION, existingProject);
@@ -150,18 +146,19 @@ public class BranchReportSubmitterTest {
     BranchSupport.ComponentKey componentKey = createComponentKeyOfBranch(createdBranch);
     when(branchSupportDelegate.createComponentKey(existingProject.getDbKey(), randomCharacteristics))
       .thenReturn(componentKey);
-    when(branchSupportDelegate.createBranchComponent(any(DbSession.class), same(componentKey), eq(organization), eq(existingProject), eq(exitingProjectMainBranch)))
+    when(branchSupportDelegate.createBranchComponent(any(DbSession.class), same(componentKey), eq(existingProject), eq(exitingProjectMainBranch)))
       .thenReturn(createdBranch);
     InputStream reportInput = IOUtils.toInputStream("{binary}", StandardCharsets.UTF_8);
     String taskUuid = mockSuccessfulPrepareSubmitCall();
 
-    underTest.submit(organization.getKey(), existingProject.getDbKey(), existingProject.name(), randomCharacteristics, reportInput);
+    underTest.submit(existingProject.getDbKey(), existingProject.name(), randomCharacteristics, reportInput);
 
     verifyNoInteractions(permissionTemplateService);
     verifyNoInteractions(favoriteUpdater);
-    verify(branchSupport).createBranchComponent(any(DbSession.class), same(componentKey), eq(organization), eq(existingProject), eq(exitingProjectMainBranch));
+    verify(branchSupport).createBranchComponent(any(DbSession.class), same(componentKey), eq(existingProject), eq(exitingProjectMainBranch));
     verify(branchSupportDelegate).createComponentKey(existingProject.getDbKey(), randomCharacteristics);
-    verify(branchSupportDelegate).createBranchComponent(any(DbSession.class), same(componentKey), eq(organization), eq(existingProject), eq(exitingProjectMainBranch));
+    verify(branchSupportDelegate).createBranchComponent(any(DbSession.class), same(componentKey), eq(existingProject),
+      eq(exitingProjectMainBranch));
     verifyNoMoreInteractions(branchSupportDelegate);
     verify(componentUpdater, times(0)).commitAndIndex(any(), any());
     verifyQueueSubmit(existingProject, createdBranch, user, randomCharacteristics, taskUuid);
@@ -169,8 +166,7 @@ public class BranchReportSubmitterTest {
 
   @Test
   public void submit_report_on_missing_branch_of_missing_project_provisions_project_when_org_PROVISION_PROJECT_perm() {
-    OrganizationDto organization = db.organizations().insert();
-    ComponentDto nonExistingProject = newPrivateProjectDto(organization);
+    ComponentDto nonExistingProject = newPrivateProjectDto(db.getDefaultOrganization());
     UserDto user = db.users().insertUser();
     userSession.logIn(user)
       .addPermission(PROVISION_PROJECTS)
@@ -183,19 +179,20 @@ public class BranchReportSubmitterTest {
       .thenReturn(componentKey);
     when(componentUpdater.createWithoutCommit(any(), any(), eq(user.getUuid()), any()))
       .thenAnswer((Answer<ComponentDto>) invocation -> db.components().insertPrivateProject(nonExistingProject));
-    when(branchSupportDelegate.createBranchComponent(any(DbSession.class), same(componentKey), eq(organization), eq(nonExistingProject), any()))
+    when(branchSupportDelegate.createBranchComponent(any(DbSession.class), same(componentKey), eq(nonExistingProject), any()))
       .thenReturn(createdBranch);
     when(permissionTemplateService.wouldUserHaveScanPermissionWithDefaultTemplate(any(DbSession.class), any(), eq(nonExistingProject.getKey())))
       .thenReturn(true);
     String taskUuid = mockSuccessfulPrepareSubmitCall();
     InputStream reportInput = IOUtils.toInputStream("{binary}", StandardCharsets.UTF_8);
 
-    underTest.submit(organization.getKey(), nonExistingProject.getDbKey(), nonExistingProject.name(), randomCharacteristics, reportInput);
+    underTest.submit(nonExistingProject.getDbKey(), nonExistingProject.name(), randomCharacteristics, reportInput);
 
     BranchDto exitingProjectMainBranch = db.getDbClient().branchDao().selectByUuid(db.getSession(), nonExistingProject.uuid()).get();
-    verify(branchSupport).createBranchComponent(any(DbSession.class), same(componentKey), eq(organization), eq(nonExistingProject), eq(exitingProjectMainBranch));
+    verify(branchSupport).createBranchComponent(any(DbSession.class), same(componentKey), eq(nonExistingProject), eq(exitingProjectMainBranch));
     verify(branchSupportDelegate).createComponentKey(nonExistingProject.getDbKey(), randomCharacteristics);
-    verify(branchSupportDelegate).createBranchComponent(any(DbSession.class), same(componentKey), eq(organization), eq(nonExistingProject), eq(exitingProjectMainBranch));
+    verify(branchSupportDelegate).createBranchComponent(any(DbSession.class), same(componentKey), eq(nonExistingProject),
+      eq(exitingProjectMainBranch));
     verifyNoMoreInteractions(branchSupportDelegate);
     verifyQueueSubmit(nonExistingProject, createdBranch, user, randomCharacteristics, taskUuid);
     verify(componentUpdater).commitAndIndex(any(DbSession.class), eq(nonExistingProject));
@@ -203,8 +200,7 @@ public class BranchReportSubmitterTest {
 
   @Test
   public void submit_fails_if_branch_support_delegate_createComponentKey_throws_an_exception() {
-    OrganizationDto organization = db.organizations().insert();
-    ComponentDto project = db.components().insertPublicProject(organization);
+    ComponentDto project = db.components().insertPublicProject();
     UserDto user = db.users().insertUser();
     userSession.logIn(user).addProjectPermission(SCAN_EXECUTION, project);
     Map<String, String> randomCharacteristics = randomNonEmptyMap();
@@ -213,47 +209,32 @@ public class BranchReportSubmitterTest {
     when(branchSupportDelegate.createComponentKey(any(), any())).thenThrow(expected);
 
     try {
-      underTest.submit(organization.getKey(), project.getDbKey(), project.name(), randomCharacteristics, reportInput);
+      underTest.submit(project.getDbKey(), project.name(), randomCharacteristics, reportInput);
       fail("exception should have been thrown");
     } catch (Exception e) {
       assertThat(e).isSameAs(expected);
     }
   }
 
-  @DataProvider
-  public static Object[][] permissionsAllowingProjectProvisioning() {
-    BiConsumer<ComponentDto, UserSessionRule> noProjectPerm = (cpt, userSession) -> {
-    };
-    BiConsumer<OrganizationDto, UserSessionRule> noOrgPerm = (cpt, userSession) -> {
-    };
-    BiConsumer<ComponentDto, UserSessionRule> provisionOnProject = (cpt, userSession) -> userSession.addProjectPermission(PROVISIONING, cpt);
-    BiConsumer<OrganizationDto, UserSessionRule> provisionOnOrganization = (cpt, userSession) -> userSession.addPermission(PROVISION_PROJECTS);
-    return new Object[][] {
-      {provisionOnProject, noOrgPerm},
-      {noProjectPerm, provisionOnOrganization},
-      {provisionOnProject, provisionOnOrganization}
-    };
-  }
-
   @Test
   public void submit_report_on_missing_branch_of_missing_project_fails_with_ForbiddenException_if_only_scan_permission() {
-    OrganizationDto organization = db.organizations().insert();
-    ComponentDto nonExistingProject = newPrivateProjectDto(organization);
+    ComponentDto nonExistingProject = newPrivateProjectDto(db.getDefaultOrganization());
     UserDto user = db.users().insertUser();
     userSession.logIn(user).addProjectPermission(SCAN_EXECUTION, nonExistingProject);
     Map<String, String> randomCharacteristics = randomNonEmptyMap();
     ComponentDto createdBranch = createButDoNotInsertBranch(nonExistingProject);
     BranchSupport.ComponentKey componentKey = createComponentKeyOfBranch(createdBranch);
-    when(branchSupportDelegate.createComponentKey(nonExistingProject.getDbKey(), randomCharacteristics))
+    String nonExistingProjectDbKey = nonExistingProject.getDbKey();
+    when(branchSupportDelegate.createComponentKey(nonExistingProjectDbKey, randomCharacteristics))
       .thenReturn(componentKey);
-    when(branchSupportDelegate.createBranchComponent(any(DbSession.class), same(componentKey), eq(organization), eq(nonExistingProject), any()))
+    when(branchSupportDelegate.createBranchComponent(any(DbSession.class), same(componentKey), eq(nonExistingProject), any()))
       .thenReturn(createdBranch);
     InputStream reportInput = IOUtils.toInputStream("{binary}", StandardCharsets.UTF_8);
 
-    expectedException.expect(ForbiddenException.class);
-    expectedException.expectMessage("Insufficient privileges");
-
-    underTest.submit(organization.getKey(), nonExistingProject.getDbKey(), nonExistingProject.name(), randomCharacteristics, reportInput);
+    String name = nonExistingProject.name();
+    assertThatThrownBy(() -> underTest.submit(nonExistingProjectDbKey, name, randomCharacteristics, reportInput))
+      .isInstanceOf(ForbiddenException.class)
+      .hasMessage("Insufficient privileges");
   }
 
   private static ComponentDto createButDoNotInsertBranch(ComponentDto project) {
index e7738b76159932f812fb91b5aded17ff1aa4ec00..9cb0c6d17ef7365d4ccbf22b7acdf3c3ef7d895f 100644 (file)
@@ -25,19 +25,17 @@ import java.util.Collections;
 import java.util.Map;
 import java.util.Random;
 import java.util.stream.IntStream;
-import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 import org.junit.runner.RunWith;
 import org.sonar.db.DbSession;
 import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.ComponentDto;
-import org.sonar.db.organization.OrganizationDto;
 import org.sonar.server.ce.queue.BranchSupport.ComponentKey;
 
 import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
 import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
@@ -46,12 +44,9 @@ import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
 public class BranchSupportTest {
   private static final Map<String, String> NO_CHARACTERISTICS = Collections.emptyMap();
 
-  @Rule
-  public ExpectedException expectedException = ExpectedException.none();
-
-  private BranchSupportDelegate branchSupportDelegate = mock(BranchSupportDelegate.class);
-  private BranchSupport underTestNoBranch = new BranchSupport();
-  private BranchSupport underTestWithBranch = new BranchSupport(branchSupportDelegate);
+  private final BranchSupportDelegate branchSupportDelegate = mock(BranchSupportDelegate.class);
+  private final BranchSupport underTestNoBranch = new BranchSupport();
+  private final BranchSupport underTestWithBranch = new BranchSupport(branchSupportDelegate);
 
   @Test
   public void createComponentKey_of_main_branch() {
@@ -84,28 +79,25 @@ public class BranchSupportTest {
   public void createBranchComponent_fails_with_ISE_if_delegate_is_null() {
     DbSession dbSession = mock(DbSession.class);
     ComponentKey componentKey = mock(ComponentKey.class);
-    OrganizationDto organization = new OrganizationDto();
     ComponentDto mainComponentDto = new ComponentDto();
     BranchDto mainComponentBranchDto = new BranchDto();
 
-    expectedException.expect(IllegalStateException.class);
-    expectedException.expectMessage("Current edition does not support branch feature");
-
-    underTestNoBranch.createBranchComponent(dbSession, componentKey, organization, mainComponentDto, mainComponentBranchDto);
+    assertThatThrownBy(() -> underTestNoBranch.createBranchComponent(dbSession, componentKey, mainComponentDto, mainComponentBranchDto))
+      .isInstanceOf(IllegalStateException.class)
+      .hasMessage("Current edition does not support branch feature");
   }
 
   @Test
   public void createBranchComponent_delegates_to_delegate() {
     DbSession dbSession = mock(DbSession.class);
     ComponentKey componentKey = mock(ComponentKey.class);
-    OrganizationDto organization = new OrganizationDto();
     ComponentDto mainComponentDto = new ComponentDto();
     ComponentDto expected = new ComponentDto();
     BranchDto mainComponentBranchDto = new BranchDto();
-    when(branchSupportDelegate.createBranchComponent(dbSession, componentKey, organization, mainComponentDto, mainComponentBranchDto))
+    when(branchSupportDelegate.createBranchComponent(dbSession, componentKey, mainComponentDto, mainComponentBranchDto))
       .thenReturn(expected);
 
-    ComponentDto dto = underTestWithBranch.createBranchComponent(dbSession, componentKey, organization, mainComponentDto, mainComponentBranchDto);
+    ComponentDto dto = underTestWithBranch.createBranchComponent(dbSession, componentKey, mainComponentDto, mainComponentBranchDto);
 
     assertThat(dto).isSameAs(expected);
   }
index ae5267ba4ec9e7890961aa43375e3fff98e1f57f..b337608639516545b0b086b3b40451fefd2434fb 100644 (file)
@@ -42,11 +42,11 @@ import static org.mockito.Mockito.when;
 public class CeQueueCleanerTest {
 
   @Rule
-  public DbTester dbTester = DbTester.create(System2.INSTANCE);
+  public final DbTester dbTester = DbTester.create(System2.INSTANCE);
 
-  private ServerUpgradeStatus serverUpgradeStatus = mock(ServerUpgradeStatus.class);
-  private CeQueue queue = mock(CeQueue.class);
-  private MapSettings settings = new MapSettings();
+  private final ServerUpgradeStatus serverUpgradeStatus = mock(ServerUpgradeStatus.class);
+  private final CeQueue queue = mock(CeQueue.class);
+  private final MapSettings settings = new MapSettings();
 
   @Test
   public void start_does_not_reset_in_progress_tasks_to_pending() {
index f6f804a808860e606ebde8d8a5eadddd2d2e97ce..f8fa8e949963774d9db423a068487ca90a412bec 100644 (file)
@@ -25,10 +25,8 @@ import java.util.Map;
 import java.util.Random;
 import java.util.stream.IntStream;
 import org.apache.commons.io.IOUtils;
-import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 import org.sonar.api.utils.System2;
 import org.sonar.ce.queue.CeQueue;
 import org.sonar.ce.queue.CeQueueImpl;
@@ -39,16 +37,15 @@ import org.sonar.db.DbSession;
 import org.sonar.db.DbTester;
 import org.sonar.db.ce.CeTaskTypes;
 import org.sonar.db.component.ComponentDto;
-import org.sonar.db.component.ComponentTesting;
-import org.sonar.db.organization.OrganizationDto;
 import org.sonar.db.permission.GlobalPermission;
 import org.sonar.db.user.UserDto;
 import org.sonar.server.component.ComponentUpdater;
 import org.sonar.server.es.TestProjectIndexers;
 import org.sonar.server.exceptions.BadRequestException;
 import org.sonar.server.exceptions.ForbiddenException;
-import org.sonar.server.exceptions.NotFoundException;
 import org.sonar.server.favorite.FavoriteUpdater;
+import org.sonar.server.organization.DefaultOrganizationProvider;
+import org.sonar.server.organization.TestDefaultOrganizationProvider;
 import org.sonar.server.permission.PermissionTemplateService;
 import org.sonar.server.tester.UserSessionRule;
 
@@ -58,13 +55,13 @@ import static java.util.Collections.emptyMap;
 import static java.util.stream.IntStream.rangeClosed;
 import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
 import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.argThat;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.verifyNoInteractions;
 import static org.mockito.Mockito.when;
 import static org.sonar.core.permission.GlobalPermissions.SCAN_EXECUTION;
 import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
@@ -80,29 +77,21 @@ public class ReportSubmitterTest {
   private static final String TASK_UUID = "TASK_1";
 
   @Rule
-  public ExpectedException expectedException = ExpectedException.none();
+  public final UserSessionRule userSession = UserSessionRule.standalone();
   @Rule
-  public UserSessionRule userSession = UserSessionRule.standalone();
-  @Rule
-  public DbTester db = DbTester.create();
+  public final DbTester db = DbTester.create();
 
-  private String defaultOrganizationKey;
-  private String defaultOrganizationUuid;
+  private final DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db);
 
-  private CeQueue queue = mock(CeQueueImpl.class);
-  private TestProjectIndexers projectIndexers = new TestProjectIndexers();
-  private PermissionTemplateService permissionTemplateService = mock(PermissionTemplateService.class);
-  private ComponentUpdater componentUpdater = new ComponentUpdater(db.getDbClient(), mock(I18n.class), mock(System2.class), permissionTemplateService,
+  private final CeQueue queue = mock(CeQueueImpl.class);
+  private final TestProjectIndexers projectIndexers = new TestProjectIndexers();
+  private final PermissionTemplateService permissionTemplateService = mock(PermissionTemplateService.class);
+  private final ComponentUpdater componentUpdater = new ComponentUpdater(db.getDbClient(), mock(I18n.class), mock(System2.class), permissionTemplateService,
     new FavoriteUpdater(db.getDbClient()), projectIndexers, new SequenceUuidFactory());
-  private BranchSupport ossEditionBranchSupport = new BranchSupport();
-
-  private ReportSubmitter underTest = new ReportSubmitter(queue, userSession, componentUpdater, permissionTemplateService, db.getDbClient(), ossEditionBranchSupport);
+  private final BranchSupport ossEditionBranchSupport = new BranchSupport();
 
-  @Before
-  public void setUp() {
-    defaultOrganizationKey = db.getDefaultOrganization().getKey();
-    defaultOrganizationUuid = db.getDefaultOrganization().getUuid();
-  }
+  private final ReportSubmitter underTest = new ReportSubmitter(queue, userSession, componentUpdater, permissionTemplateService, db.getDbClient(), ossEditionBranchSupport,
+    defaultOrganizationProvider);
 
   @Test
   public void submit_with_characteristics_fails_with_ISE_when_no_branch_support_delegate() {
@@ -117,10 +106,9 @@ public class ReportSubmitterTest {
       .collect(uniqueIndex(i -> randomAlphabetic(i + 10), i -> randomAlphabetic(i + 20)));
     InputStream reportInput = IOUtils.toInputStream("{binary}", UTF_8);
 
-    expectedException.expect(IllegalStateException.class);
-    expectedException.expectMessage("Current edition does not support branch feature");
-
-    underTest.submit(defaultOrganizationKey, PROJECT_KEY, PROJECT_NAME, nonEmptyCharacteristics, reportInput);
+    assertThatThrownBy(() -> underTest.submit(PROJECT_KEY, PROJECT_NAME, nonEmptyCharacteristics, reportInput))
+      .isInstanceOf(IllegalStateException.class)
+      .hasMessage("Current edition does not support branch feature");
   }
 
   @Test
@@ -132,22 +120,22 @@ public class ReportSubmitterTest {
     when(permissionTemplateService.wouldUserHaveScanPermissionWithDefaultTemplate(any(), any(), eq(PROJECT_KEY)))
       .thenReturn(true);
 
-    underTest.submit(defaultOrganizationKey, PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}", UTF_8));
+    underTest.submit(PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}", UTF_8));
 
     verifyReportIsPersisted(TASK_UUID);
   }
 
   @Test
   public void submit_a_report_on_existing_project() {
-    ComponentDto project = db.components().insertPrivateProject(db.getDefaultOrganization());
+    ComponentDto project = db.components().insertPrivateProject();
     UserDto user = db.users().insertUser();
     userSession.logIn(user).addProjectPermission(SCAN_EXECUTION, project);
     mockSuccessfulPrepareSubmitCall();
 
-    underTest.submit(defaultOrganizationKey, project.getDbKey(), project.name(), emptyMap(), IOUtils.toInputStream("{binary}", StandardCharsets.UTF_8));
+    underTest.submit(project.getDbKey(), project.name(), emptyMap(), IOUtils.toInputStream("{binary}", StandardCharsets.UTF_8));
 
     verifyReportIsPersisted(TASK_UUID);
-    verifyZeroInteractions(permissionTemplateService);
+    verifyNoInteractions(permissionTemplateService);
     verify(queue).submit(argThat(submit -> submit.getType().equals(CeTaskTypes.REPORT)
       && submit.getComponent().filter(cpt -> cpt.getUuid().equals(project.uuid()) && cpt.getMainComponentUuid().equals(project.uuid())).isPresent()
       && submit.getSubmitterUuid().equals(user.getUuid())
@@ -156,7 +144,6 @@ public class ReportSubmitterTest {
 
   @Test
   public void provision_project_if_does_not_exist() {
-    OrganizationDto organization = db.organizations().insert();
     userSession
       .addPermission(GlobalPermission.SCAN)
       .addPermission(PROVISION_PROJECTS);
@@ -164,7 +151,7 @@ public class ReportSubmitterTest {
     when(permissionTemplateService.wouldUserHaveScanPermissionWithDefaultTemplate(any(DbSession.class), any(), eq(PROJECT_KEY))).thenReturn(true);
     when(permissionTemplateService.hasDefaultTemplateWithPermissionOnProjectCreator(any(DbSession.class), any(ComponentDto.class))).thenReturn(true);
 
-    underTest.submit(organization.getKey(), PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
+    underTest.submit(PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
 
     ComponentDto createdProject = db.getDbClient().componentDao().selectByKey(db.getSession(), PROJECT_KEY).get();
     verifyReportIsPersisted(TASK_UUID);
@@ -176,7 +163,6 @@ public class ReportSubmitterTest {
   @Test
   public void add_project_as_favorite_when_project_creator_permission_on_permission_template() {
     UserDto user = db.users().insertUser();
-    OrganizationDto organization = db.organizations().insert();
     userSession
       .logIn(user)
       .addPermission(GlobalPermission.SCAN)
@@ -185,7 +171,7 @@ public class ReportSubmitterTest {
     when(permissionTemplateService.wouldUserHaveScanPermissionWithDefaultTemplate(any(DbSession.class), any(), eq(PROJECT_KEY))).thenReturn(true);
     when(permissionTemplateService.hasDefaultTemplateWithPermissionOnProjectCreator(any(DbSession.class), any(ComponentDto.class))).thenReturn(true);
 
-    underTest.submit(organization.getKey(), PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
+    underTest.submit(PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
 
     ComponentDto createdProject = db.getDbClient().componentDao().selectByKey(db.getSession(), PROJECT_KEY).get();
     assertThat(db.favorites().hasFavorite(createdProject, user.getUuid())).isTrue();
@@ -201,7 +187,7 @@ public class ReportSubmitterTest {
     when(permissionTemplateService.hasDefaultTemplateWithPermissionOnProjectCreator(any(DbSession.class), any(ComponentDto.class))).thenReturn(false);
     mockSuccessfulPrepareSubmitCall();
 
-    underTest.submit(defaultOrganizationKey, PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
+    underTest.submit(PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
 
     ComponentDto createdProject = db.getDbClient().componentDao().selectByKey(db.getSession(), PROJECT_KEY).get();
     assertThat(db.favorites().hasNoFavorite(createdProject)).isTrue();
@@ -211,7 +197,6 @@ public class ReportSubmitterTest {
   public void do_no_add_favorite_when_already_100_favorite_projects_and_no_project_creator_permission_on_permission_template() {
     UserDto user = db.users().insertUser();
     rangeClosed(1, 100).forEach(i -> db.favorites().add(db.components().insertPrivateProject(), user.getUuid()));
-    OrganizationDto organization = db.organizations().insert();
     userSession
       .logIn(user)
       .addPermission(GlobalPermission.SCAN)
@@ -220,14 +205,14 @@ public class ReportSubmitterTest {
     when(permissionTemplateService.wouldUserHaveScanPermissionWithDefaultTemplate(any(DbSession.class), any(), eq(PROJECT_KEY))).thenReturn(true);
     when(permissionTemplateService.hasDefaultTemplateWithPermissionOnProjectCreator(any(DbSession.class), any(ComponentDto.class))).thenReturn(true);
 
-    underTest.submit(organization.getKey(), PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
+    underTest.submit(PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
 
     ComponentDto createdProject = db.getDbClient().componentDao().selectByKey(db.getSession(), PROJECT_KEY).get();
     assertThat(db.favorites().hasNoFavorite(createdProject)).isTrue();
   }
 
   @Test
-  public void submit_a_report_on_new_project_with_scan_permission_on_organization() {
+  public void submit_a_report_on_new_project_with_scan_permission() {
     userSession
       .addPermission(GlobalPermission.SCAN)
       .addPermission(PROVISION_PROJECTS);
@@ -235,97 +220,86 @@ public class ReportSubmitterTest {
     when(permissionTemplateService.wouldUserHaveScanPermissionWithDefaultTemplate(any(DbSession.class), any(), eq(PROJECT_KEY)))
       .thenReturn(true);
 
-    underTest.submit(defaultOrganizationKey, PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
+    underTest.submit(PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
 
     verify(queue).submit(any(CeTaskSubmit.class));
   }
 
   @Test
-  public void user_with_scan_permission_on_organization_is_allowed_to_submit_a_report_on_existing_project() {
-    OrganizationDto org = db.organizations().insert();
-    ComponentDto project = db.components().insertPrivateProject(org);
+  public void user_with_scan_permission_is_allowed_to_submit_a_report_on_existing_project() {
+    ComponentDto project = db.components().insertPrivateProject();
     userSession.addPermission(SCAN);
     mockSuccessfulPrepareSubmitCall();
 
-    underTest.submit(org.getKey(), project.getDbKey(), project.name(), emptyMap(), IOUtils.toInputStream("{binary}"));
+    underTest.submit(project.getDbKey(), project.name(), emptyMap(), IOUtils.toInputStream("{binary}"));
 
     verify(queue).submit(any(CeTaskSubmit.class));
   }
 
   @Test
   public void submit_a_report_on_existing_project_with_project_scan_permission() {
-    ComponentDto project = db.components().insertPrivateProject(db.getDefaultOrganization());
+    ComponentDto project = db.components().insertPrivateProject();
     userSession.addProjectPermission(SCAN_EXECUTION, project);
     mockSuccessfulPrepareSubmitCall();
 
-    underTest.submit(defaultOrganizationKey, project.getDbKey(), project.name(), emptyMap(), IOUtils.toInputStream("{binary}"));
+    underTest.submit(project.getDbKey(), project.name(), emptyMap(), IOUtils.toInputStream("{binary}"));
 
     verify(queue).submit(any(CeTaskSubmit.class));
   }
 
-  @Test
-  public void fail_with_NotFoundException_if_organization_with_specified_key_does_not_exist() {
-    expectedException.expect(NotFoundException.class);
-    expectedException.expectMessage("Organization with key 'fop' does not exist");
-
-    underTest.submit("fop", PROJECT_KEY, null, emptyMap(), null /* method will fail before parameter is used */);
-  }
-
-  @Test
-  public void fail_with_organizationKey_does_not_match_organization_of_specified_component() {
-    userSession.logIn().setRoot();
-    OrganizationDto organization = db.organizations().insert();
-    ComponentDto project = db.components().insertPrivateProject(organization);
-    mockSuccessfulPrepareSubmitCall();
-
-    underTest.submit(organization.getKey(), project.getDbKey(), project.name(), emptyMap(), IOUtils.toInputStream("{binary}"));
-  }
-
   @Test
   public void fail_if_component_is_not_a_project() {
-    ComponentDto component = db.components().insertPublicPortfolio(db.getDefaultOrganization());
+    ComponentDto component = db.components().insertPublicPortfolio();
     userSession.logIn().addProjectPermission(SCAN_EXECUTION, component);
     mockSuccessfulPrepareSubmitCall();
 
-    expectedException.expect(BadRequestException.class);
-    expectedException.expectMessage(format("Component '%s' is not a project", component.getKey()));
-
-    underTest.submit(defaultOrganizationKey, component.getDbKey(), component.name(), emptyMap(), IOUtils.toInputStream("{binary}"));
+    String dbKey = component.getDbKey();
+    String name = component.name();
+    Map<String, String> emptyMap = emptyMap();
+    InputStream stream = IOUtils.toInputStream("{binary}", UTF_8);
+    assertThatThrownBy(() -> underTest.submit(dbKey, name, emptyMap, stream))
+      .isInstanceOf(BadRequestException.class)
+      .hasMessage(format("Component '%s' is not a project", component.getKey()));
   }
 
   @Test
   public void fail_if_project_key_already_exists_as_module() {
-    ComponentDto project = db.components().insertPrivateProject(db.getDefaultOrganization());
+    ComponentDto project = db.components().insertPrivateProject();
     ComponentDto module = db.components().insertComponent(newModuleDto(project));
     userSession.logIn().addProjectPermission(SCAN_EXECUTION, project);
     mockSuccessfulPrepareSubmitCall();
 
-    try {
-      underTest.submit(defaultOrganizationKey, module.getDbKey(), module.name(), emptyMap(), IOUtils.toInputStream("{binary}"));
-      fail();
-    } catch (BadRequestException e) {
-      assertThat(e.errors()).contains(
-        format("The project '%s' is already defined in SonarQube but as a module of project '%s'. " +
-            "If you really want to stop directly analysing project '%s', please first delete it from SonarQube and then relaunch the analysis of project '%s'.",
-          module.getKey(), project.getKey(), project.getKey(), module.getKey()));
-    }
+    String moduleDbKey = module.getDbKey();
+    String name = module.name();
+    Map<String, String> emptyMap = emptyMap();
+    InputStream inputStream = IOUtils.toInputStream("{binary}", UTF_8);
+    assertThatThrownBy(() -> underTest.submit(moduleDbKey, name, emptyMap, inputStream))
+      .isInstanceOf(BadRequestException.class)
+      .extracting(throwable -> ((BadRequestException) throwable).errors())
+      .asList()
+      .contains(format("The project '%s' is already defined in SonarQube but as a module of project '%s'. " +
+        "If you really want to stop directly analysing project '%s', please first delete it from SonarQube and then relaunch the analysis of project '%s'.",
+        module.getKey(), project.getKey(), project.getKey(), module.getKey()));
   }
 
   @Test
   public void fail_with_forbidden_exception_when_no_scan_permission() {
-    expectedException.expect(ForbiddenException.class);
-
-    underTest.submit(defaultOrganizationKey, PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
+    Map<String, String> emptyMap = emptyMap();
+    InputStream inputStream = IOUtils.toInputStream("{binary}", UTF_8);
+    assertThatThrownBy(() -> underTest.submit(PROJECT_KEY, PROJECT_NAME, emptyMap, inputStream))
+      .isInstanceOf(ForbiddenException.class);
   }
 
   @Test
   public void fail_with_forbidden_exception_on_new_project_when_only_project_scan_permission() {
-    ComponentDto component = ComponentTesting.newPrivateProjectDto(db.getDefaultOrganization(), PROJECT_UUID);
+    ComponentDto component = db.components().insertPrivateProject(PROJECT_UUID);
     userSession.addProjectPermission(SCAN_EXECUTION, component);
     mockSuccessfulPrepareSubmitCall();
 
-    expectedException.expect(ForbiddenException.class);
-    underTest.submit(defaultOrganizationKey, PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
+    Map<String, String> emptyMap = emptyMap();
+    InputStream inputStream = IOUtils.toInputStream("{binary}", UTF_8);
+    assertThatThrownBy(() -> underTest.submit(PROJECT_KEY, PROJECT_NAME, emptyMap, inputStream))
+      .isInstanceOf(ForbiddenException.class);
   }
 
   private void verifyReportIsPersisted(String taskUuid) {
index 165582467ebef1e48f0137267afd587b73c69340..d7d0c08160af1661c8eb0c7651bdd34c4e89ba8d 100644 (file)
@@ -26,7 +26,6 @@ import java.util.stream.IntStream;
 import javax.annotation.Nullable;
 import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 import org.sonar.api.server.ws.WebService.Param;
 import org.sonar.api.utils.System2;
 import org.sonar.api.web.UserRole;
@@ -43,7 +42,6 @@ import org.sonar.db.ce.CeTaskTypes;
 import org.sonar.db.component.BranchType;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.component.SnapshotDto;
-import org.sonar.db.organization.OrganizationDto;
 import org.sonar.server.exceptions.BadRequestException;
 import org.sonar.server.exceptions.ForbiddenException;
 import org.sonar.server.exceptions.NotFoundException;
@@ -62,6 +60,7 @@ import org.sonarqube.ws.MediaTypes;
 import static java.util.Arrays.asList;
 import static java.util.Collections.emptyList;
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.assertj.core.api.Assertions.tuple;
 import static org.mockito.Mockito.mock;
 import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY;
@@ -85,8 +84,6 @@ public class ActivityActionTest {
 
   private static final long EXECUTED_AT = System2.INSTANCE.now();
 
-  @Rule
-  public ExpectedException expectedException = ExpectedException.none();
   @Rule
   public UserSessionRule userSession = UserSessionRule.standalone();
   @Rule
@@ -99,10 +96,8 @@ public class ActivityActionTest {
   @Test
   public void get_all_past_activity() {
     logInAsSystemAdministrator();
-    OrganizationDto org1 = db.organizations().insert();
-    ComponentDto project1 = db.components().insertPrivateProject(org1);
-    OrganizationDto org2 = db.organizations().insert();
-    ComponentDto project2 = db.components().insertPrivateProject(org2);
+    ComponentDto project1 = db.components().insertPrivateProject();
+    ComponentDto project2 = db.components().insertPrivateProject();
     SnapshotDto analysisProject1 = db.components().insertSnapshot(project1);
     insertActivity("T1", project1, SUCCESS, analysisProject1);
     insertActivity("T2", project2, FAILED, null);
@@ -113,7 +108,6 @@ public class ActivityActionTest {
     assertThat(activityResponse.getTasksCount()).isEqualTo(2);
     // chronological order, from newest to oldest
     Task task = activityResponse.getTasks(0);
-    assertThat(task.getOrganization()).isEqualTo(org2.getKey());
     assertThat(task.getId()).isEqualTo("T2");
     assertThat(task.getStatus()).isEqualTo(Ce.TaskStatus.FAILED);
     assertThat(task.getComponentId()).isEqualTo(project2.uuid());
@@ -127,7 +121,6 @@ public class ActivityActionTest {
     assertThat(task.getStatus()).isEqualTo(Ce.TaskStatus.SUCCESS);
     assertThat(task.getComponentId()).isEqualTo(project1.uuid());
     assertThat(task.getLogs()).isFalse();
-    assertThat(task.getOrganization()).isEqualTo(org1.getKey());
     assertThat(task.getWarningCount()).isZero();
   }
 
@@ -290,10 +283,10 @@ public class ActivityActionTest {
     ComponentDto project = db.components().insertPrivateProject();
     userSession.anonymous();
 
-    expectedException.expect(UnauthorizedException.class);
-    expectedException.expectMessage("Authentication is required");
-
-    call(ws.newRequest().setParam("componentId", project.uuid()));
+    TestRequest request = ws.newRequest().setParam("componentId", project.uuid());
+    assertThatThrownBy(() -> call(request))
+      .isInstanceOf(UnauthorizedException.class)
+      .hasMessage("Authentication is required");
   }
 
   @Test
@@ -374,10 +367,10 @@ public class ActivityActionTest {
     insertActivity("T1", view, SUCCESS);
     userSession.logIn().addProjectPermission(UserRole.ADMIN, view);
 
-    expectedException.expect(ForbiddenException.class);
-    expectedException.expectMessage("Insufficient privileges");
-
-    call(ws.newRequest().setParam(Param.TEXT_QUERY, "T1"));
+    TestRequest request = ws.newRequest().setParam(TEXT_QUERY, "T1");
+    assertThatThrownBy(() -> call(request))
+      .isInstanceOf(ForbiddenException.class)
+      .hasMessage("Insufficient privileges");
   }
 
   @Test
@@ -477,83 +470,80 @@ public class ActivityActionTest {
 
   @Test
   public void fail_if_both_component_id_and_component_key_provided() {
-    expectedException.expect(BadRequestException.class);
-    expectedException.expectMessage("componentId and component must not be set at the same time");
-
-    ws.newRequest()
+    TestRequest request = ws.newRequest()
       .setParam("componentId", "ID1")
       .setParam("component", "apache")
-      .setMediaType(MediaTypes.PROTOBUF)
-      .execute();
+      .setMediaType(MediaTypes.PROTOBUF);
+    assertThatThrownBy(request::execute)
+      .isInstanceOf(BadRequestException.class)
+      .hasMessage("componentId and component must not be set at the same time");
   }
 
   @Test
   public void fail_if_both_filters_on_component_key_and_name() {
-    expectedException.expect(BadRequestException.class);
-    expectedException.expectMessage("component and q must not be set at the same time");
-
-    ws.newRequest()
+    TestRequest request = ws.newRequest()
       .setParam("q", "apache")
       .setParam("component", "apache")
-      .setMediaType(MediaTypes.PROTOBUF)
-      .execute();
+      .setMediaType(MediaTypes.PROTOBUF);
+    assertThatThrownBy(request::execute)
+      .isInstanceOf(BadRequestException.class)
+      .hasMessage("component and q must not be set at the same time");
   }
 
   @Test
   public void fail_if_both_filters_on_component_id_and_name() {
-    expectedException.expect(BadRequestException.class);
-    expectedException.expectMessage("componentId and q must not be set at the same time");
-
-    ws.newRequest()
+    TestRequest request = ws.newRequest()
       .setParam("componentId", "ID1")
       .setParam("q", "apache")
-      .setMediaType(MediaTypes.PROTOBUF)
-      .execute();
+      .setMediaType(MediaTypes.PROTOBUF);
+
+    assertThatThrownBy(request::execute)
+      .isInstanceOf(BadRequestException.class)
+      .hasMessage("componentId and q must not be set at the same time");
   }
 
   @Test
   public void fail_if_page_size_greater_than_1000() {
-    expectedException.expect(IllegalArgumentException.class);
-    expectedException.expectMessage("'ps' value (1001) must be less than 1000");
+    TestRequest request = ws.newRequest()
+      .setParam(Param.PAGE_SIZE, "1001");
 
-    ws.newRequest()
-      .setParam(Param.PAGE_SIZE, "1001")
-      .execute();
+    assertThatThrownBy(request::execute)
+      .isInstanceOf(IllegalArgumentException.class)
+      .hasMessage("'ps' value (1001) must be less than 1000");
   }
 
   @Test
   public void fail_if_date_is_not_well_formatted() {
     logInAsSystemAdministrator();
 
-    expectedException.expect(IllegalArgumentException.class);
-    expectedException.expectMessage("Date 'ill-formatted-date' cannot be parsed as either a date or date+time");
+    TestRequest request = ws.newRequest()
+      .setParam(PARAM_MAX_EXECUTED_AT, "ill-formatted-date");
 
-    ws.newRequest()
-      .setParam(PARAM_MAX_EXECUTED_AT, "ill-formatted-date")
-      .execute();
+    assertThatThrownBy(request::execute)
+      .isInstanceOf(IllegalArgumentException.class)
+      .hasMessage("Date 'ill-formatted-date' cannot be parsed as either a date or date+time");
   }
 
   @Test
   public void throws_IAE_if_pageSize_is_0() {
     logInAsSystemAdministrator();
-    expectedException.expect(IllegalArgumentException.class);
-    expectedException.expectMessage("page size must be >= 1");
-
-    call(ws.newRequest()
+    TestRequest request = ws.newRequest()
       .setParam(Param.PAGE_SIZE, Integer.toString(0))
-      .setParam(PARAM_STATUS, "SUCCESS,FAILED,CANCELED,IN_PROGRESS,PENDING"));
+      .setParam(PARAM_STATUS, "SUCCESS,FAILED,CANCELED,IN_PROGRESS,PENDING");
+    assertThatThrownBy(() -> call(request))
+      .isInstanceOf(IllegalArgumentException.class)
+      .hasMessage("page size must be >= 1");
+
   }
 
   @Test
   public void fail_when_project_does_not_exist() {
     logInAsSystemAdministrator();
 
-    expectedException.expect(NotFoundException.class);
-    expectedException.expectMessage("Component 'unknown' does not exist");
-
-    ws.newRequest()
-      .setParam(PARAM_COMPONENT_ID, "unknown")
-      .execute();
+    TestRequest request = ws.newRequest().setParam(PARAM_COMPONENT_ID, "unknown");
+    assertThatThrownBy(request::execute)
+      .isInstanceOf(NotFoundException.class)
+      .hasMessage("Component 'unknown' does not exist");
   }
 
   private void assertPage(int pageSize, List<String> expectedOrderedTaskIds) {
@@ -579,7 +569,7 @@ public class ActivityActionTest {
   }
 
   @Test
-  public void filter_out_duplicate_tasks_in_progress_and_success(){
+  public void filter_out_duplicate_tasks_in_progress_and_success() {
     logInAsSystemAdministrator();
     ComponentDto project1 = db.components().insertPrivateProject();
     ComponentDto project2 = db.components().insertPrivateProject();
@@ -593,7 +583,7 @@ public class ActivityActionTest {
 
     assertThat(response.getTasksList())
       .extracting(Task::getId)
-      .containsExactlyInAnyOrder("T1","T2","T3");
+      .containsExactlyInAnyOrder("T1", "T2", "T3");
   }
 
   private void logInAsSystemAdministrator() {
index a3038fa8c63b43a2cdc14e519f6ae45925fc30bf..efa1fc4146c14cf6125fa8c7924a6358fa64e2d3 100644 (file)
@@ -22,7 +22,6 @@ package org.sonar.server.ce.ws;
 import javax.annotation.Nullable;
 import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 import org.sonar.api.server.ws.WebService;
 import org.sonar.api.utils.System2;
 import org.sonar.api.web.UserRole;
@@ -34,7 +33,6 @@ import org.sonar.db.ce.CeActivityDto;
 import org.sonar.db.ce.CeQueueDto;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.component.ComponentTesting;
-import org.sonar.db.organization.OrganizationDto;
 import org.sonar.server.component.TestComponentFinder;
 import org.sonar.server.exceptions.ForbiddenException;
 import org.sonar.server.exceptions.NotFoundException;
@@ -44,6 +42,7 @@ import org.sonar.server.ws.WsActionTester;
 import org.sonarqube.ws.Ce;
 
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 import static org.sonar.db.ce.CeQueueTesting.newCeQueueDto;
@@ -54,8 +53,6 @@ import static org.sonar.test.JsonAssert.assertJson;
 
 public class ActivityStatusActionTest {
 
-  @Rule
-  public ExpectedException expectedException = ExpectedException.none();
   @Rule
   public UserSessionRule userSession = UserSessionRule.standalone().logIn().setSystemAdministrator();
   @Rule
@@ -97,11 +94,10 @@ public class ActivityStatusActionTest {
   public void status_for_a_project_as_project_admin() {
     String projectUuid = "project-uuid";
     String anotherProjectUuid = "another-project-uuid";
-    OrganizationDto organizationDto = db.organizations().insert();
-    ComponentDto project = newPrivateProjectDto(organizationDto, projectUuid);
-    ComponentDto anotherProject = newPrivateProjectDto(organizationDto, anotherProjectUuid);
+    ComponentDto project = newPrivateProjectDto(db.getDefaultOrganization(), projectUuid);
+    ComponentDto anotherProject = newPrivateProjectDto(db.getDefaultOrganization(), anotherProjectUuid);
     db.components().insertComponent(project);
-    db.components().insertComponent(newPrivateProjectDto(organizationDto, anotherProjectUuid));
+    db.components().insertComponent(newPrivateProjectDto(db.getDefaultOrganization(), anotherProjectUuid));
     userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
     // pending tasks returned
     insertInQueue(CeQueueDto.Status.PENDING, project);
@@ -126,8 +122,7 @@ public class ActivityStatusActionTest {
   @Test
   public void add_pending_time() {
     String projectUuid = "project-uuid";
-    OrganizationDto organizationDto = db.organizations().insert();
-    ComponentDto project = newPrivateProjectDto(organizationDto, projectUuid);
+    ComponentDto project = newPrivateProjectDto(db.getDefaultOrganization(), projectUuid);
     db.components().insertComponent(project);
 
     userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
@@ -150,35 +145,34 @@ public class ActivityStatusActionTest {
 
   @Test
   public void fail_if_component_uuid_and_key_are_provided() {
-    ComponentDto project = ComponentTesting.newPrivateProjectDto(db.organizations().insert());
+    ComponentDto project = ComponentTesting.newPrivateProjectDto();
     db.components().insertComponent(project);
-    expectedException.expect(IllegalArgumentException.class);
 
-    callByComponentUuidOrComponentKey(project.uuid(), project.getDbKey());
+    String uuid = project.uuid();
+    String dbKey = project.getDbKey();
+    assertThatThrownBy(() -> callByComponentUuidOrComponentKey(uuid, dbKey))
+      .isInstanceOf(IllegalArgumentException.class);
   }
 
   @Test
   public void fail_if_component_uuid_is_unknown() {
-    expectedException.expect(NotFoundException.class);
-
-    call("unknown-uuid");
+    assertThatThrownBy(() -> call("unknown-uuid"))
+      .isInstanceOf(NotFoundException.class);
   }
 
   @Test
   public void fail_if_component_key_is_unknown() {
-    expectedException.expect(NotFoundException.class);
-
-    callByComponentKey("unknown-key");
+    assertThatThrownBy(() -> callByComponentKey("unknown-key"))
+      .isInstanceOf(NotFoundException.class);
   }
 
   @Test
   public void throw_ForbiddenException_if_not_root() {
     userSession.logIn();
 
-    expectedException.expect(ForbiddenException.class);
-    expectedException.expectMessage("Insufficient privileges");
-
-    call();
+    assertThatThrownBy(this::call)
+      .isInstanceOf(ForbiddenException.class)
+      .hasMessage("Insufficient privileges");
   }
 
   @Test
@@ -186,10 +180,10 @@ public class ActivityStatusActionTest {
     userSession.logIn();
     ComponentDto project = db.components().insertPrivateProject();
 
-    expectedException.expect(ForbiddenException.class);
-    expectedException.expectMessage("Insufficient privileges");
-
-    callByComponentKey(project.getDbKey());
+    String dbKey = project.getDbKey();
+    assertThatThrownBy(() -> callByComponentKey(dbKey))
+      .isInstanceOf(ForbiddenException.class)
+      .hasMessage("Insufficient privileges");
   }
 
   private void insertInQueue(CeQueueDto.Status status, @Nullable ComponentDto componentDto) {
index 56460ab7531e33ac0a65ae78de1b2195cb0f5987..4264580c852cecc17c8ae45086da8e0fbcffc01f 100644 (file)
@@ -22,7 +22,6 @@ package org.sonar.server.ce.ws;
 import javax.annotation.Nullable;
 import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 import org.sonar.api.utils.System2;
 import org.sonar.api.web.UserRole;
 import org.sonar.db.DbClient;
@@ -34,16 +33,17 @@ import org.sonar.db.ce.CeTaskMessageType;
 import org.sonar.db.component.BranchType;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.component.SnapshotDto;
-import org.sonar.db.organization.OrganizationDto;
 import org.sonar.server.component.TestComponentFinder;
 import org.sonar.server.exceptions.BadRequestException;
 import org.sonar.server.exceptions.NotFoundException;
 import org.sonar.server.tester.UserSessionRule;
+import org.sonar.server.ws.TestRequest;
 import org.sonar.server.ws.WsActionTester;
 import org.sonarqube.ws.Ce;
 import org.sonarqube.ws.Ce.AnalysisStatusWsResponse.Warning;
 
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.assertj.core.api.Assertions.tuple;
 import static org.sonar.db.ce.CeActivityDto.Status.SUCCESS;
 import static org.sonar.db.ce.CeTaskTypes.REPORT;
@@ -63,8 +63,6 @@ public class AnalysisStatusActionTest {
 
   private static int counter = 1;
 
-  @Rule
-  public ExpectedException expectedException = ExpectedException.none();
   @Rule
   public UserSessionRule userSession = UserSessionRule.standalone();
   @Rule
@@ -87,7 +85,7 @@ public class AnalysisStatusActionTest {
 
   @Test
   public void allows_unauthenticated_access() {
-    ComponentDto project = db.components().insertPublicProject(db.getDefaultOrganization());
+    ComponentDto project = db.components().insertPublicProject();
     userSession.registerComponents(project);
     SnapshotDto analysis = db.components().insertSnapshot(project);
     CeActivityDto activity = insertActivity("task-uuid" + counter++, project, SUCCESS, analysis, REPORT);
@@ -295,10 +293,8 @@ public class AnalysisStatusActionTest {
 
   @Test
   public void json_example() {
-    OrganizationDto organization = db.organizations().insert(o -> o.setKey("my-org-1"));
-    ComponentDto project = db.components().insertPrivateProject(organization,
-      p -> p.setDbKey("com.github.kevinsawicki:http-request-parent")
-        .setName("HttpRequest"));
+    ComponentDto project = db.components().insertPrivateProject(p -> p.setDbKey("com.github.kevinsawicki:http-request-parent")
+      .setName("HttpRequest"));
     SnapshotDto analysis = db.components().insertSnapshot(project);
     CeActivityDto activity = insertActivity("task-uuid" + counter++, project, SUCCESS, analysis, REPORT);
     CeTaskMessageDto ceTaskMessage = new CeTaskMessageDto()
@@ -322,27 +318,27 @@ public class AnalysisStatusActionTest {
 
   @Test
   public void fail_if_component_key_not_provided() {
-    expectedException.expect(IllegalArgumentException.class);
-
-    ws.newRequest().execute();
+    TestRequest request = ws.newRequest();
+    assertThatThrownBy(request::execute)
+      .isInstanceOf(IllegalArgumentException.class);
   }
 
   @Test
   public void fail_if_component_key_is_unknown() {
-    expectedException.expect(NotFoundException.class);
-
-    ws.newRequest().setParam(PARAM_COMPONENT, "nonexistent").execute();
+    TestRequest request = ws.newRequest().setParam(PARAM_COMPONENT, "nonexistent");
+    assertThatThrownBy(request::execute)
+      .isInstanceOf(NotFoundException.class);
   }
 
   @Test
   public void fail_if_both_branch_and_pullRequest_are_specified() {
-    expectedException.expect(BadRequestException.class);
-
-    ws.newRequest()
+    TestRequest request = ws.newRequest()
       .setParam(PARAM_COMPONENT, "dummy")
       .setParam(PARAM_BRANCH, "feature1")
-      .setParam(PARAM_PULL_REQUEST, "pr1")
-      .execute();
+      .setParam(PARAM_PULL_REQUEST, "pr1");
+
+    assertThatThrownBy(request::execute)
+      .isInstanceOf(BadRequestException.class);
   }
 
   private CeTaskMessageDto createTaskMessage(CeActivityDto activity, String warning) {
index 63e870d36209bdeaa2d4c00e9baa828fd7087fbd..5be9a4c596f72a9810d324c66bdbf2cfb79e5a5e 100644 (file)
@@ -23,7 +23,6 @@ import org.junit.Test;
 import org.mockito.Mockito;
 import org.sonar.api.server.ws.WebService;
 import org.sonar.server.ce.queue.ReportSubmitter;
-import org.sonar.server.organization.DefaultOrganizationProvider;
 
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.mockito.Mockito.mock;
@@ -32,7 +31,7 @@ public class CeWsTest {
 
   @Test
   public void define() {
-    CeWsAction wsAction = new SubmitAction(mock(ReportSubmitter.class), mock(DefaultOrganizationProvider.class));
+    CeWsAction wsAction = new SubmitAction(mock(ReportSubmitter.class));
 
     CeWs ws = new CeWs(wsAction);
     WebService.Context context = mock(WebService.Context.class, Mockito.RETURNS_DEEP_STUBS);
index 759f86258b854142ab84b4f012fda464214c4501..51bd83efdafd3847bb6c5a31db748194b4e9640b 100644 (file)
@@ -25,7 +25,6 @@ import java.util.stream.IntStream;
 import javax.annotation.Nullable;
 import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 import org.sonar.api.utils.System2;
 import org.sonar.api.web.UserRole;
 import org.sonar.core.util.Uuids;
@@ -38,11 +37,11 @@ import org.sonar.db.ce.CeTaskMessageType;
 import org.sonar.db.ce.CeTaskTypes;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.component.SnapshotDto;
-import org.sonar.db.organization.OrganizationDto;
 import org.sonar.server.component.TestComponentFinder;
 import org.sonar.server.exceptions.ForbiddenException;
 import org.sonar.server.exceptions.NotFoundException;
 import org.sonar.server.tester.UserSessionRule;
+import org.sonar.server.ws.TestRequest;
 import org.sonar.server.ws.WsActionTester;
 import org.sonarqube.ws.Ce;
 import org.sonarqube.ws.Common;
@@ -50,6 +49,7 @@ import org.sonarqube.ws.MediaTypes;
 
 import static java.util.Collections.emptyList;
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.assertj.core.api.Assertions.tuple;
 import static org.sonar.db.ce.CeActivityDto.Status.SUCCESS;
 import static org.sonar.db.ce.CeQueueDto.Status.IN_PROGRESS;
@@ -62,8 +62,6 @@ import static org.sonar.server.ce.ws.CeWsParameters.PARAM_COMPONENT_ID;
 
 public class ComponentActionTest {
 
-  @Rule
-  public ExpectedException expectedException = ExpectedException.none();
   @Rule
   public UserSessionRule userSession = UserSessionRule.standalone();
   @Rule
@@ -88,10 +86,9 @@ public class ComponentActionTest {
 
   @Test
   public void project_tasks() {
-    OrganizationDto organization = db.organizations().insert();
-    ComponentDto project1 = db.components().insertPrivateProject(organization);
+    ComponentDto project1 = db.components().insertPrivateProject();
     SnapshotDto analysisProject1 = db.components().insertSnapshot(project1);
-    ComponentDto project2 = db.components().insertPrivateProject(organization);
+    ComponentDto project2 = db.components().insertPrivateProject();
     userSession.addProjectPermission(UserRole.USER, project1);
     insertActivity("T1", project1, CeActivityDto.Status.SUCCESS, analysisProject1);
     insertActivity("T2", project2, CeActivityDto.Status.FAILED, null);
@@ -112,10 +109,6 @@ public class ComponentActionTest {
     assertThat(current.hasAnalysisId()).isFalse();
     assertThat(current.getWarningCount()).isZero();
     assertThat(current.getWarningsList()).isEmpty();
-    assertThat(response.getQueueList())
-      .extracting(Ce.Task::getOrganization)
-      .containsOnly(organization.getKey());
-    assertThat(current.getOrganization()).isEqualTo(organization.getKey());
   }
 
   @Test
@@ -286,11 +279,11 @@ public class ComponentActionTest {
 
   @Test
   public void fail_with_404_when_component_does_not_exist() {
-    expectedException.expect(NotFoundException.class);
-    ws.newRequest()
+    TestRequest request = ws.newRequest()
       .setParam(PARAM_COMPONENT, "UNKNOWN")
-      .setMediaType(MediaTypes.PROTOBUF)
-      .execute();
+      .setMediaType(MediaTypes.PROTOBUF);
+    assertThatThrownBy(request::execute)
+      .isInstanceOf(NotFoundException.class);
   }
 
   @Test
@@ -298,20 +291,21 @@ public class ComponentActionTest {
     ComponentDto project = db.components().insertPrivateProject();
     userSession.logIn();
 
-    expectedException.expect(ForbiddenException.class);
-    expectedException.expectMessage("Insufficient privileges");
+    TestRequest request = ws.newRequest()
+      .setParam(PARAM_COMPONENT, project.getKey());
 
-    ws.newRequest()
-      .setParam(PARAM_COMPONENT, project.getKey())
-      .execute();
+    assertThatThrownBy(request::execute)
+      .isInstanceOf(ForbiddenException.class)
+      .hasMessage("Insufficient privileges");
   }
 
   @Test
   public void fail_when_no_component_parameter() {
-    expectedException.expect(IllegalArgumentException.class);
     logInWithBrowsePermission(db.components().insertPrivateProject());
 
-    ws.newRequest().execute();
+    TestRequest request = ws.newRequest();
+    assertThatThrownBy(request::execute)
+      .isInstanceOf(IllegalArgumentException.class);
   }
 
   private void logInWithBrowsePermission(ComponentDto project) {
index 8fce2030533f01a4427c90de52122bf34e754541..d98b6a7f6da675f376f3299595c847a42a38c6ed 100644 (file)
@@ -27,8 +27,6 @@ import org.mockito.ArgumentCaptor;
 import org.sonar.ce.task.CeTask;
 import org.sonar.db.ce.CeTaskTypes;
 import org.sonar.server.ce.queue.ReportSubmitter;
-import org.sonar.server.organization.DefaultOrganizationProvider;
-import org.sonar.server.organization.TestDefaultOrganizationProvider;
 import org.sonar.server.ws.TestResponse;
 import org.sonar.server.ws.WsActionTester;
 import org.sonar.test.JsonAssert;
@@ -58,16 +56,15 @@ public class SubmitActionTest {
     .setSubmitter(new CeTask.User("UUID_1", "LOGIN_1"))
     .build();
 
-  private ArgumentCaptor<Map<String, String>> map = ArgumentCaptor.forClass(Map.class);
-  private DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.fromUuid("org1");
-  private String organizationKey = defaultOrganizationProvider.get().getKey();
-  private ReportSubmitter reportSubmitter = mock(ReportSubmitter.class);
-  private SubmitAction underTest = new SubmitAction(reportSubmitter, defaultOrganizationProvider);
-  private WsActionTester tester = new WsActionTester(underTest);
+  private final ArgumentCaptor<Map<String, String>> map = ArgumentCaptor.forClass(Map.class);
+
+  private final ReportSubmitter reportSubmitter = mock(ReportSubmitter.class);
+  private final SubmitAction underTest = new SubmitAction(reportSubmitter);
+  private final WsActionTester tester = new WsActionTester(underTest);
 
   @Test
   public void submit_task_to_the_queue_and_ask_for_immediate_processing() {
-    when(reportSubmitter.submit(eq(organizationKey), eq("my_project"), eq("My Project"), anyMap(), any())).thenReturn(A_CE_TASK);
+    when(reportSubmitter.submit(eq("my_project"), eq("My Project"), anyMap(), any())).thenReturn(A_CE_TASK);
 
     Ce.SubmitResponse submitResponse = tester.newRequest()
       .setParam("projectKey", "my_project")
@@ -76,7 +73,7 @@ public class SubmitActionTest {
       .setMethod("POST")
       .executeProtobuf(Ce.SubmitResponse.class);
 
-    verify(reportSubmitter).submit(eq(organizationKey), eq("my_project"), eq("My Project"), anyMap(), any());
+    verify(reportSubmitter).submit(eq("my_project"), eq("My Project"), anyMap(), any());
 
     assertThat(submitResponse.getTaskId()).isEqualTo("TASK_1");
     assertThat(submitResponse.getProjectId()).isEqualTo(PROJECT_UUID);
@@ -84,7 +81,7 @@ public class SubmitActionTest {
 
   @Test
   public void submit_task_with_characteristics() {
-    when(reportSubmitter.submit(eq(organizationKey), eq("my_project"), eq("My Project"), anyMap(), any())).thenReturn(A_CE_TASK);
+    when(reportSubmitter.submit(eq("my_project"), eq("My Project"), anyMap(), any())).thenReturn(A_CE_TASK);
 
     String[] characteristics = {"branch=foo", "pullRequest=123", "unsupported=bar"};
     Ce.SubmitResponse submitResponse = tester.newRequest()
@@ -96,7 +93,7 @@ public class SubmitActionTest {
       .executeProtobuf(Ce.SubmitResponse.class);
 
     assertThat(submitResponse.getTaskId()).isEqualTo("TASK_1");
-    verify(reportSubmitter).submit(eq(organizationKey), eq("my_project"), eq("My Project"), map.capture(), any());
+    verify(reportSubmitter).submit(eq("my_project"), eq("My Project"), map.capture(), any());
 
     // unsupported characteristics are ignored
     assertThat(map.getValue()).containsExactly(entry("branch", "foo"), entry("pullRequest", "123"));
@@ -106,7 +103,7 @@ public class SubmitActionTest {
   public void abbreviate_long_name() {
     String longName = Strings.repeat("a", 1_000);
     String expectedName = Strings.repeat("a", 497) + "...";
-    when(reportSubmitter.submit(eq(organizationKey), eq("my_project"), eq(expectedName), anyMap(), any())).thenReturn(A_CE_TASK);
+    when(reportSubmitter.submit(eq("my_project"), eq(expectedName), anyMap(), any())).thenReturn(A_CE_TASK);
 
     Ce.SubmitResponse submitResponse = tester.newRequest()
       .setParam("projectKey", "my_project")
@@ -115,7 +112,7 @@ public class SubmitActionTest {
       .setMethod("POST")
       .executeProtobuf(Ce.SubmitResponse.class);
 
-    verify(reportSubmitter).submit(eq(organizationKey), eq("my_project"), eq(expectedName), anyMap(), any());
+    verify(reportSubmitter).submit(eq("my_project"), eq(expectedName), anyMap(), any());
 
     assertThat(submitResponse.getTaskId()).isEqualTo("TASK_1");
     assertThat(submitResponse.getProjectId()).isEqualTo(PROJECT_UUID);
@@ -123,7 +120,7 @@ public class SubmitActionTest {
 
   @Test
   public void test_example_json_response() {
-    when(reportSubmitter.submit(eq(organizationKey), eq("my_project"), eq("My Project"), anyMap(), any())).thenReturn(A_CE_TASK);
+    when(reportSubmitter.submit(eq("my_project"), eq("My Project"), anyMap(), any())).thenReturn(A_CE_TASK);
 
     TestResponse wsResponse = tester.newRequest()
       .setParam("projectKey", "my_project")
@@ -141,7 +138,7 @@ public class SubmitActionTest {
    */
   @Test
   public void project_name_is_optional() {
-    when(reportSubmitter.submit(eq(organizationKey), eq("my_project"), eq("my_project"), anyMap(), any())).thenReturn(A_CE_TASK);
+    when(reportSubmitter.submit(eq("my_project"), eq("my_project"), anyMap(), any())).thenReturn(A_CE_TASK);
 
     tester.newRequest()
       .setParam("projectKey", "my_project")
@@ -150,6 +147,6 @@ public class SubmitActionTest {
       .setMethod("POST")
       .execute();
 
-    verify(reportSubmitter).submit(eq(organizationKey), eq("my_project"), eq("my_project"), anyMap(), any());
+    verify(reportSubmitter).submit(eq("my_project"), eq("my_project"), anyMap(), any());
   }
 }
index 9f2ebe3f4078a9f9672a0b14f71efae20bbd42ce..98961801c1489707f187d46e4e84aa79862e7162 100644 (file)
@@ -26,7 +26,6 @@ import javax.annotation.Nullable;
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 import org.sonar.api.utils.System2;
 import org.sonar.api.web.UserRole;
 import org.sonar.core.permission.GlobalPermissions;
@@ -41,18 +40,19 @@ import org.sonar.db.ce.CeTaskMessageDto;
 import org.sonar.db.ce.CeTaskMessageType;
 import org.sonar.db.ce.CeTaskTypes;
 import org.sonar.db.component.ComponentDto;
-import org.sonar.db.organization.OrganizationDto;
 import org.sonar.db.permission.GlobalPermission;
 import org.sonar.db.user.UserDto;
 import org.sonar.server.exceptions.ForbiddenException;
 import org.sonar.server.exceptions.NotFoundException;
 import org.sonar.server.tester.UserSessionRule;
+import org.sonar.server.ws.TestRequest;
 import org.sonar.server.ws.WsActionTester;
 import org.sonarqube.ws.Ce;
 import org.sonarqube.ws.Common;
 
 import static java.util.Collections.singleton;
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.sonar.core.permission.GlobalPermissions.SCAN_EXECUTION;
 import static org.sonar.db.ce.CeTaskCharacteristicDto.BRANCH_KEY;
 import static org.sonar.db.ce.CeTaskCharacteristicDto.BRANCH_TYPE_KEY;
@@ -64,26 +64,22 @@ public class TaskActionTest {
   private static final String SOME_TASK_UUID = "TASK_1";
 
   @Rule
-  public UserSessionRule userSession = UserSessionRule.standalone();
+  public final UserSessionRule userSession = UserSessionRule.standalone();
 
   @Rule
-  public ExpectedException expectedException = ExpectedException.none();
+  public final DbTester db = DbTester.create(System2.INSTANCE);
 
-  @Rule
-  public DbTester db = DbTester.create(System2.INSTANCE);
-
-  private OrganizationDto organization;
-  private ComponentDto privateProject;
-  private ComponentDto publicProject;
   private final TaskFormatter formatter = new TaskFormatter(db.getDbClient(), System2.INSTANCE);
   private final TaskAction underTest = new TaskAction(db.getDbClient(), formatter, userSession);
   private final WsActionTester ws = new WsActionTester(underTest);
 
+  private ComponentDto privateProject;
+  private ComponentDto publicProject;
+
   @Before
   public void setUp() {
-    organization = db.organizations().insert();
-    privateProject = db.components().insertPrivateProject(organization);
-    publicProject = db.components().insertPublicProject(organization);
+    privateProject = db.components().insertPrivateProject();
+    publicProject = db.components().insertPublicProject();
   }
 
   @Test
@@ -102,7 +98,6 @@ public class TaskActionTest {
     Ce.TaskResponse taskResponse = ws.newRequest()
       .setParam("id", SOME_TASK_UUID)
       .executeProtobuf(Ce.TaskResponse.class);
-    assertThat(taskResponse.getTask().getOrganization()).isEqualTo(organization.getKey());
     assertThat(taskResponse.getTask().getId()).isEqualTo(SOME_TASK_UUID);
     assertThat(taskResponse.getTask().getStatus()).isEqualTo(Ce.TaskStatus.PENDING);
     assertThat(taskResponse.getTask().getSubmitterLogin()).isEqualTo(user.getLogin());
@@ -150,7 +145,6 @@ public class TaskActionTest {
       .setParam("id", SOME_TASK_UUID)
       .executeProtobuf(Ce.TaskResponse.class);
     Ce.Task task = taskResponse.getTask();
-    assertThat(task.getOrganization()).isEqualTo(organization.getKey());
     assertThat(task.getId()).isEqualTo(SOME_TASK_UUID);
     assertThat(task.getStatus()).isEqualTo(Ce.TaskStatus.FAILED);
     assertThat(task.getComponentId()).isEqualTo(privateProject.uuid());
@@ -294,11 +288,10 @@ public class TaskActionTest {
   public void throw_NotFoundException_if_id_does_not_exist() {
     logInAsRoot();
 
-    expectedException.expect(NotFoundException.class);
-
-    ws.newRequest()
-      .setParam("id", "DOES_NOT_EXIST")
-      .execute();
+    TestRequest request = ws.newRequest()
+      .setParam("id", "DOES_NOT_EXIST");
+    assertThatThrownBy(request::execute)
+      .isInstanceOf(NotFoundException.class);
   }
 
   @Test
@@ -316,9 +309,9 @@ public class TaskActionTest {
     userSession.logIn().registerComponents(publicProject);
     CeQueueDto task = createAndPersistQueueTask(publicProject, user);
 
-    expectedException.expect(ForbiddenException.class);
-
-    call(task.getUuid());
+    String uuid = task.getUuid();
+    assertThatThrownBy(() -> call(uuid))
+      .isInstanceOf(ForbiddenException.class);
   }
 
   @Test
@@ -327,9 +320,9 @@ public class TaskActionTest {
     userSession.logIn().addProjectPermission(UserRole.USER, privateProject);
     CeQueueDto task = createAndPersistQueueTask(privateProject, user);
 
-    expectedException.expect(ForbiddenException.class);
-
-    call(task.getUuid());
+    String uuid = task.getUuid();
+    assertThatThrownBy(() -> call(uuid))
+      .isInstanceOf(ForbiddenException.class);
   }
 
   @Test
@@ -342,7 +335,7 @@ public class TaskActionTest {
   }
 
   @Test
-  public void get_project_queue_task_with_scan_permission_on_organization_but_not_on_project() {
+  public void get_project_queue_task_with_scan_permission_but_not_on_project() {
     UserDto user = db.users().insertUser();
     userSession.logIn(user).addPermission(SCAN);
     CeQueueDto task = createAndPersistQueueTask(privateProject, user);
@@ -356,9 +349,9 @@ public class TaskActionTest {
     userSession.logIn(user);
     CeQueueDto task = createAndPersistQueueTask(privateProject, user);
 
-    expectedException.expect(ForbiddenException.class);
-
-    call(task.getUuid());
+    String uuid = task.getUuid();
+    assertThatThrownBy(() -> call(uuid))
+      .isInstanceOf(ForbiddenException.class);
   }
 
   @Test
@@ -376,9 +369,9 @@ public class TaskActionTest {
     userSession.logIn(user).setNonSystemAdministrator();
     CeQueueDto task = createAndPersistQueueTask(null, user);
 
-    expectedException.expect(ForbiddenException.class);
-
-    call(task.getUuid());
+    String uuid = task.getUuid();
+    assertThatThrownBy(() -> call(uuid))
+      .isInstanceOf(ForbiddenException.class);
   }
 
   @Test
@@ -394,13 +387,13 @@ public class TaskActionTest {
     userSession.logIn().registerComponents(publicProject);
     CeActivityDto task = createAndPersistArchivedTask(publicProject);
 
-    expectedException.expect(ForbiddenException.class);
-
-    call(task.getUuid());
+    String uuid = task.getUuid();
+    assertThatThrownBy(() -> call(uuid))
+      .isInstanceOf(ForbiddenException.class);
   }
 
   @Test
-  public void get_project_archived_task_with_scan_permission_on_organization_but_not_on_project() {
+  public void get_project_archived_task_with_scan_permission_but_not_on_project() {
     userSession.logIn().addPermission(SCAN);
     CeActivityDto task = createAndPersistArchivedTask(privateProject);
 
@@ -412,9 +405,9 @@ public class TaskActionTest {
     userSession.logIn();
     CeActivityDto task = createAndPersistArchivedTask(privateProject);
 
-    expectedException.expect(ForbiddenException.class);
-
-    call(task.getUuid());
+    String uuid = task.getUuid();
+    assertThatThrownBy(() -> call(uuid))
+      .isInstanceOf(ForbiddenException.class);
   }
 
   @Test
@@ -430,9 +423,9 @@ public class TaskActionTest {
     userSession.logIn().setNonSystemAdministrator();
     CeActivityDto task = createAndPersistArchivedTask(null);
 
-    expectedException.expect(ForbiddenException.class);
-
-    call(task.getUuid());
+    String uuid = task.getUuid();
+    assertThatThrownBy(() -> call(uuid))
+      .isInstanceOf(ForbiddenException.class);
   }
 
   @Test
@@ -446,18 +439,18 @@ public class TaskActionTest {
   public void get_warnings_on_public_project_archived_task_if_not_admin_fails_with_ForbiddenException() {
     userSession.logIn().registerComponents(publicProject);
 
-    expectedException.expect(ForbiddenException.class);
-
-    getWarningsImpl(createAndPersistArchivedTask(publicProject));
+    CeActivityDto persistArchivedTask = createAndPersistArchivedTask(publicProject);
+    assertThatThrownBy(() -> getWarningsImpl(persistArchivedTask))
+      .isInstanceOf(ForbiddenException.class);
   }
 
   @Test
   public void get_warnings_on_private_project_archived_task_if_user_fails_with_ForbiddenException() {
     userSession.logIn().addProjectPermission(UserRole.USER, privateProject);
 
-    expectedException.expect(ForbiddenException.class);
-
-    getWarningsImpl(createAndPersistArchivedTask(privateProject));
+    CeActivityDto persistArchivedTask = createAndPersistArchivedTask(privateProject);
+    assertThatThrownBy(() -> getWarningsImpl(persistArchivedTask))
+      .isInstanceOf(ForbiddenException.class);
   }
 
   @Test
@@ -468,7 +461,7 @@ public class TaskActionTest {
   }
 
   @Test
-  public void get_warnings_on_private_project_archived_task_if_scan_on_organization() {
+  public void get_warnings_on_private_project_archived_task_if_global_scan_permission() {
     userSession.logIn().addPermission(GlobalPermission.SCAN);
 
     getWarningsImpl(createAndPersistArchivedTask(privateProject));
index 6ef3d0ccba3df7e3cf926552f4757544bd37fab2..38f62b4f5a33c59fe1b7302346d6fd449fd82335 100644 (file)
@@ -27,14 +27,13 @@ import java.util.stream.IntStream;
 import javax.annotation.Nullable;
 import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 import org.sonar.api.utils.DateUtils;
 import org.sonar.api.utils.System2;
+import org.sonar.db.DbSession;
 import org.sonar.db.DbTester;
 import org.sonar.db.ce.CeActivityDto;
 import org.sonar.db.ce.CeQueueDto;
 import org.sonar.db.ce.CeTaskTypes;
-import org.sonar.db.organization.OrganizationDto;
 import org.sonar.db.user.UserDto;
 import org.sonarqube.ws.Ce;
 
@@ -42,6 +41,7 @@ import static java.util.Arrays.asList;
 import static java.util.Collections.emptyList;
 import static java.util.stream.Collectors.toList;
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.assertj.core.api.Assertions.tuple;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
@@ -51,13 +51,11 @@ public class TaskFormatterTest {
 
   @Rule
   public DbTester db = DbTester.create(System2.INSTANCE);
-  @Rule
-  public ExpectedException expectedException = ExpectedException.none();
 
-  private int warningCount = new Random().nextInt(10);
+  private final int warningCount = new Random().nextInt(10);
 
-  private System2 system2 = mock(System2.class);
-  private TaskFormatter underTest = new TaskFormatter(db.getDbClient(), system2);
+  private final System2 system2 = mock(System2.class);
+  private final TaskFormatter underTest = new TaskFormatter(db.getDbClient(), system2);
 
   @Test
   public void formatQueue_without_component() {
@@ -89,8 +87,7 @@ public class TaskFormatterTest {
   @Test
   public void formatQueue_with_component_and_other_fields() {
     String uuid = "COMPONENT_UUID";
-    OrganizationDto organizationDto = db.organizations().insert();
-    db.components().insertPrivateProject(organizationDto, (t) -> t.setUuid(uuid).setDbKey("COMPONENT_KEY").setName("Component Name"));
+    db.components().insertPrivateProject((t) -> t.setUuid(uuid).setDbKey("COMPONENT_KEY").setName("Component Name"));
     UserDto user = db.users().insertUser();
 
     CeQueueDto dto = new CeQueueDto();
@@ -178,9 +175,9 @@ public class TaskFormatterTest {
     UserDto user = db.users().insertUser();
     CeActivityDto dto = newActivity("UUID", "COMPONENT_UUID", CeActivityDto.Status.FAILED, user);
 
-    expectedException.expect(NullPointerException.class);
-
-    underTest.formatActivity(db.getSession(), dto, "foo", null);
+    DbSession dbSession = db.getSession();
+    assertThatThrownBy(() -> underTest.formatActivity(dbSession, dto, "foo", null))
+      .isInstanceOf(NullPointerException.class);
   }
 
   @Test
index 2c083fbbec6fda35247d33a3fc48cda58d8024f8..cd16545ae8bc5c3c70ea2a7d0d4c8a44b55aa456 100644 (file)
@@ -64,12 +64,11 @@ message AnalysisStatusWsResponse {
   optional Component component = 1;
 
   message Component {
-    optional string organization = 1;
-    optional string key = 2;
-    optional string name = 3;
-    repeated Warning warnings = 4;
-    optional string branch = 5;
-    optional string pullRequest = 6;
+    optional string key = 1;
+    optional string name = 2;
+    repeated Warning warnings = 3;
+    optional string branch = 4;
+    optional string pullRequest = 5;
   }
 
   message Warning {
@@ -127,14 +126,13 @@ message Task {
   optional string errorStacktrace = 17;
   optional string scannerContext = 18;
   optional bool hasScannerContext = 19;
-  optional string organization = 20;
-  optional string branch = 21;
-  optional sonarqube.ws.commons.BranchType branchType = 22;
-  optional string errorType = 23;
-  optional string pullRequest = 24;
-  optional string pullRequestTitle = 25;
-  optional int32 warningCount = 26;
-  repeated string warnings = 27;
+  optional string branch = 20;
+  optional sonarqube.ws.commons.BranchType branchType = 21;
+  optional string errorType = 22;
+  optional string pullRequest = 23;
+  optional string pullRequestTitle = 24;
+  optional int32 warningCount = 25;
+  repeated string warnings = 26;
 }
 
 enum TaskStatus {