diff --git a/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/DtoConverter.java b/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/DtoConverter.java index c6376bd4be3..bb8f8c8f5ad 100644 --- a/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/DtoConverter.java +++ b/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/DtoConverter.java @@ -48,8 +48,6 @@ import org.eclipse.che.api.workspace.shared.dto.stack.StackSourceDto; import org.eclipse.che.api.workspace.shared.stack.Stack; import org.eclipse.che.api.workspace.shared.stack.StackSource; -import org.eclipse.che.commons.env.EnvironmentContext; -import org.eclipse.che.commons.subject.Subject; import org.eclipse.che.dto.server.DtoFactory; /** @@ -61,7 +59,6 @@ public final class DtoConverter { /** Converts {@link Workspace} to {@link WorkspaceDto}. */ public static WorkspaceDto asDto(Workspace workspace) { - Subject subject = EnvironmentContext.getCurrent().getSubject(); WorkspaceDto workspaceDto = newDto(WorkspaceDto.class) .withId(workspace.getId()) @@ -73,7 +70,6 @@ public static WorkspaceDto asDto(Workspace workspace) { if (workspace.getRuntime() != null) { RuntimeDto runtime = asDto(workspace.getRuntime()); - runtime.setUserToken(subject.getToken()); workspaceDto.setRuntime(runtime); } diff --git a/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/WorkspaceService.java b/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/WorkspaceService.java index 648d6895339..af1bd8fd189 100644 --- a/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/WorkspaceService.java +++ b/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/WorkspaceService.java @@ -39,9 +39,7 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; import org.eclipse.che.api.core.BadRequestException; import org.eclipse.che.api.core.ConflictException; import org.eclipse.che.api.core.ForbiddenException; @@ -54,10 +52,13 @@ import org.eclipse.che.api.workspace.server.model.impl.EnvironmentImpl; import org.eclipse.che.api.workspace.server.model.impl.ProjectConfigImpl; import org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl; +import org.eclipse.che.api.workspace.server.token.MachineTokenException; +import org.eclipse.che.api.workspace.server.token.MachineTokenProvider; import org.eclipse.che.api.workspace.shared.dto.CommandDto; import org.eclipse.che.api.workspace.shared.dto.EnvironmentDto; import org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto; import org.eclipse.che.api.workspace.shared.dto.RecipeDto; +import org.eclipse.che.api.workspace.shared.dto.RuntimeDto; import org.eclipse.che.api.workspace.shared.dto.WorkspaceConfigDto; import org.eclipse.che.api.workspace.shared.dto.WorkspaceDto; import org.eclipse.che.commons.env.EnvironmentContext; @@ -73,25 +74,20 @@ public class WorkspaceService extends Service { private final WorkspaceManager workspaceManager; + private final MachineTokenProvider machineTokenProvider; private final WorkspaceLinksGenerator linksGenerator; private final String apiEndpoint; - // private final boolean cheWorkspaceAutoSnapshot; - // private final boolean cheWorkspaceAutoRestore; - @Context private SecurityContext securityContext; @Inject public WorkspaceService( @Named("che.api") String apiEndpoint, WorkspaceManager workspaceManager, - WorkspaceLinksGenerator linksGenerator - // @Named(CHE_WORKSPACE_AUTO_SNAPSHOT) boolean cheWorkspaceAutoSnapshot, - // @Named(CHE_WORKSPACE_AUTO_RESTORE) boolean cheWorkspaceAutoRestore - ) { + MachineTokenProvider machineTokenProvider, + WorkspaceLinksGenerator linksGenerator) { this.apiEndpoint = apiEndpoint; this.workspaceManager = workspaceManager; + this.machineTokenProvider = machineTokenProvider; this.linksGenerator = linksGenerator; - // this.cheWorkspaceAutoSnapshot = cheWorkspaceAutoSnapshot; - // this.cheWorkspaceAutoRestore = cheWorkspaceAutoRestore; } @POST @@ -158,7 +154,7 @@ public Response create( if (startAfterCreate) { workspaceManager.startWorkspace(workspace.getId(), null, new HashMap<>()); } - return Response.status(201).entity(asDtoWithLinks(workspace)).build(); + return Response.status(201).entity(asDtoWithLinksAndToken(workspace)).build(); } @GET @@ -191,7 +187,7 @@ public WorkspaceDto getByKey( String key) throws NotFoundException, ServerException, ForbiddenException, BadRequestException { validateKey(key); - return asDtoWithLinks(workspaceManager.getWorkspace(key)); + return asDtoWithLinksAndToken(workspaceManager.getWorkspace(key)); } @GET @@ -278,7 +274,7 @@ public WorkspaceDto update( ConflictException { requiredNotNull(update, "Workspace configuration"); relativizeRecipeLinks(update.getConfig()); - return doUpdate(id, update); + return asDtoWithLinksAndToken(doUpdate(id, update)); } @DELETE @@ -331,7 +327,7 @@ public WorkspaceDto startById( Map options = new HashMap<>(); if (restore != null) options.put("restore", restore.toString()); - return asDtoWithLinks(workspaceManager.startWorkspace(workspaceId, envName, options)); + return asDtoWithLinksAndToken(workspaceManager.startWorkspace(workspaceId, envName, options)); } @POST @@ -380,7 +376,7 @@ public WorkspaceDto startFromConfig( try { Workspace workspace = workspaceManager.startWorkspace(config, namespace, isTemporary, new HashMap<>()); - return asDtoWithLinks(workspace); + return asDtoWithLinksAndToken(workspace); } catch (ValidationException x) { throw new BadRequestException(x.getMessage()); } @@ -436,7 +432,7 @@ public WorkspaceDto addCommand( requiredNotNull(newCommand, "Command"); WorkspaceImpl workspace = workspaceManager.getWorkspace(id); workspace.getConfig().getCommands().add(new CommandImpl(newCommand)); - return doUpdate(id, workspace); + return asDtoWithLinksAndToken(doUpdate(id, workspace)); } @PUT @@ -469,7 +465,7 @@ public WorkspaceDto updateCommand( format("Workspace '%s' doesn't contain command '%s'", id, cmdName)); } commands.add(new CommandImpl(update)); - return doUpdate(id, workspace); + return asDtoWithLinksAndToken(doUpdate(id, workspace)); } @DELETE @@ -526,7 +522,7 @@ public WorkspaceDto addEnvironment( relativizeRecipeLinks(newEnvironment); WorkspaceImpl workspace = workspaceManager.getWorkspace(id); workspace.getConfig().getEnvironments().put(envName, new EnvironmentImpl(newEnvironment)); - return doUpdate(id, workspace); + return asDtoWithLinksAndToken(doUpdate(id, workspace)); } @PUT @@ -559,7 +555,7 @@ public WorkspaceDto updateEnvironment( throw new NotFoundException( format("Workspace '%s' doesn't contain environment '%s'", id, envName)); } - return doUpdate(id, workspace); + return asDtoWithLinksAndToken(doUpdate(id, workspace)); } @DELETE @@ -609,7 +605,7 @@ public WorkspaceDto addProject( requiredNotNull(newProject, "New project config"); final WorkspaceImpl workspace = workspaceManager.getWorkspace(id); workspace.getConfig().getProjects().add(new ProjectConfigImpl(newProject)); - return doUpdate(id, workspace); + return asDtoWithLinksAndToken(doUpdate(id, workspace)); } @PUT @@ -642,7 +638,7 @@ public WorkspaceDto updateProject( format("Workspace '%s' doesn't contain project with path '%s'", id, normalizedPath)); } projects.add(new ProjectConfigImpl(update)); - return doUpdate(id, workspace); + return asDtoWithLinksAndToken(doUpdate(id, workspace)); } @DELETE @@ -679,8 +675,6 @@ public void deleteProject( @ApiResponses({@ApiResponse(code = 200, message = "The response contains server settings")}) public Map getSettings() { return new HashMap<>(); - // return ImmutableMap.of(CHE_WORKSPACE_AUTO_SNAPSHOT, Boolean.toString(cheWorkspaceAutoSnapshot), - // CHE_WORKSPACE_AUTO_RESTORE, Boolean.toString(cheWorkspaceAutoRestore)); } private static Map parseAttrs(List attributes) @@ -782,10 +776,10 @@ private void relativizeRecipeLinks(EnvironmentDto environment) { } } - private WorkspaceDto doUpdate(String id, Workspace update) + private Workspace doUpdate(String id, Workspace update) throws BadRequestException, ConflictException, NotFoundException, ServerException { try { - return asDtoWithLinks(workspaceManager.updateWorkspace(id, update)); + return workspaceManager.updateWorkspace(id, update); } catch (ValidationException x) { throw new BadRequestException(x.getMessage()); } @@ -798,7 +792,18 @@ private List withLinks(List workspaces) throws Serve return workspaces; } - private WorkspaceDto asDtoWithLinks(Workspace workspace) throws ServerException { - return asDto(workspace).withLinks(linksGenerator.genLinks(workspace)); + private WorkspaceDto asDtoWithLinksAndToken(Workspace workspace) throws ServerException { + WorkspaceDto workspaceDto = asDto(workspace).withLinks(linksGenerator.genLinks(workspace)); + + RuntimeDto runtimeDto = workspaceDto.getRuntime(); + if (runtimeDto != null) { + try { + runtimeDto.setUserToken(machineTokenProvider.getToken(workspace.getId())); + } catch (MachineTokenException e) { + throw new ServerException(e.getMessage(), e); + } + } + + return workspaceDto; } } diff --git a/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/model/impl/RuntimeImpl.java b/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/model/impl/RuntimeImpl.java index a91de77df4c..f8bcdb47b83 100644 --- a/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/model/impl/RuntimeImpl.java +++ b/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/model/impl/RuntimeImpl.java @@ -26,16 +26,14 @@ public class RuntimeImpl implements Runtime { private final String activeEnv; - private String owner; - private String userToken; - private Map machines; + private final String owner; + private final Map machines; private List warnings; public RuntimeImpl(String activeEnv, Map machines, String owner) { this.activeEnv = activeEnv; this.machines = machines; this.owner = owner; - // this.userToken = userToken; } public RuntimeImpl(Runtime runtime) { @@ -47,7 +45,6 @@ public RuntimeImpl(Runtime runtime) { .stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> new MachineImpl(e.getValue()))); this.owner = runtime.getOwner(); - // this.userToken = null; this.warnings = runtime.getWarnings().stream().map(WarningImpl::new).collect(Collectors.toList()); } @@ -70,14 +67,6 @@ public List getWarnings() { return warnings; } - public String getUserToken() { - return userToken; - } - - public void setUserToken(String userToken) { - this.userToken = userToken; - } - @Override public Map getMachines() { return machines; @@ -89,19 +78,14 @@ public boolean equals(Object o) { if (!(o instanceof RuntimeImpl)) return false; RuntimeImpl that = (RuntimeImpl) o; return Objects.equals(activeEnv, that.activeEnv) - && - // Objects.equals(rootFolder, that.rootFolder) && - // Objects.equals(devMachine, that.devMachine) && - Objects.equals(machines, that.machines); + && Objects.equals(machines, that.machines) + && Objects.equals(owner, that.owner) + && Objects.equals(warnings, that.warnings); } @Override public int hashCode() { - return Objects.hash( - activeEnv, - // rootFolder, - // devMachine, - machines); + return Objects.hash(activeEnv, machines, owner, warnings); } @Override @@ -110,11 +94,13 @@ public String toString() { + "activeEnv='" + activeEnv + '\'' - + - // ", rootFolder='" + rootFolder + '\'' + - // ", devMachine=" + devMachine + - ", machines=" + + ", owner='" + + owner + + '\'' + + ", machines=" + machines + + ", warnings=" + + warnings + '}'; } } diff --git a/wsmaster/che-core-api-workspace/src/test/java/org/eclipse/che/api/workspace/server/WorkspaceServiceTest.java b/wsmaster/che-core-api-workspace/src/test/java/org/eclipse/che/api/workspace/server/WorkspaceServiceTest.java index 2c4cf0c87a5..80427bece1c 100644 --- a/wsmaster/che-core-api-workspace/src/test/java/org/eclipse/che/api/workspace/server/WorkspaceServiceTest.java +++ b/wsmaster/che-core-api-workspace/src/test/java/org/eclipse/che/api/workspace/server/WorkspaceServiceTest.java @@ -10,937 +10,939 @@ */ package org.eclipse.che.api.workspace.server; +import static com.jayway.restassured.RestAssured.given; +import static java.util.Arrays.asList; +import static java.util.Collections.emptyList; +import static java.util.Collections.emptyMap; +import static java.util.Collections.singleton; +import static java.util.Collections.singletonList; +import static java.util.Collections.singletonMap; +import static java.util.stream.Collectors.toList; +import static org.eclipse.che.api.core.model.workspace.WorkspaceStatus.STARTING; +import static org.eclipse.che.dto.server.DtoFactory.newDto; +import static org.everrest.assured.JettyHttpServer.ADMIN_USER_NAME; +import static org.everrest.assured.JettyHttpServer.ADMIN_USER_PASSWORD; +import static org.everrest.assured.JettyHttpServer.SECURE_PATH; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyBoolean; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.testng.Assert.assertEquals; + +import com.google.common.collect.ImmutableMap; +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import com.jayway.restassured.response.Response; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.eclipse.che.account.shared.model.Account; +import org.eclipse.che.account.spi.AccountImpl; +import org.eclipse.che.api.core.model.workspace.WorkspaceConfig; +import org.eclipse.che.api.core.model.workspace.WorkspaceStatus; +import org.eclipse.che.api.core.model.workspace.config.ProjectConfig; +import org.eclipse.che.api.core.rest.ApiExceptionMapper; +import org.eclipse.che.api.core.rest.shared.dto.ServiceError; +import org.eclipse.che.api.workspace.server.model.impl.CommandImpl; +import org.eclipse.che.api.workspace.server.model.impl.EnvironmentImpl; +import org.eclipse.che.api.workspace.server.model.impl.MachineConfigImpl; +import org.eclipse.che.api.workspace.server.model.impl.RecipeImpl; +import org.eclipse.che.api.workspace.server.model.impl.RuntimeImpl; +import org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl; +import org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl; +import org.eclipse.che.api.workspace.server.token.MachineTokenProvider; +import org.eclipse.che.api.workspace.shared.dto.CommandDto; +import org.eclipse.che.api.workspace.shared.dto.EnvironmentDto; +import org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto; +import org.eclipse.che.api.workspace.shared.dto.SourceStorageDto; +import org.eclipse.che.api.workspace.shared.dto.WorkspaceConfigDto; +import org.eclipse.che.api.workspace.shared.dto.WorkspaceDto; +import org.eclipse.che.commons.env.EnvironmentContext; +import org.eclipse.che.commons.subject.SubjectImpl; +import org.eclipse.che.dto.server.DtoFactory; import org.everrest.assured.EverrestJetty; +import org.everrest.core.Filter; +import org.everrest.core.GenericContainerRequest; +import org.everrest.core.RequestFilter; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; import org.mockito.testng.MockitoTestNGListener; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; import org.testng.annotations.Listeners; +import org.testng.annotations.Test; /** * Tests for {@link WorkspaceService}. * * @author Yevhenii Voevodin + * @author Sergii Leshchenko */ @Listeners(value = {EverrestJetty.class, MockitoTestNGListener.class}) public class WorkspaceServiceTest { - // @SuppressWarnings("unused") - // private static final ApiExceptionMapper MAPPER = new ApiExceptionMapper(); - // private static final String NAMESPACE = "user"; - // private static final String USER_ID = "user123"; - // private static final String API_ENDPOINT = "http://localhost:8080/api"; - // private static final Account TEST_ACCOUNT = new AccountImpl("anyId", NAMESPACE, "test"); - // @SuppressWarnings("unused") - // private static final EnvironmentFilter FILTER = new EnvironmentFilter(); - // - // @Mock - // private WorkspaceManager wsManager; - // @Mock - // private MachineProcessManager machineProcessManager; - // @Mock - // private WorkspaceValidator validator; - // @Mock - // private WsAgentHealthChecker wsAgentHealthChecker; - // - // private WorkspaceService service; - // - // @BeforeMethod - // public void setup() { - // service = new WorkspaceService(API_ENDPOINT, - // wsManager, - // validator, - // wsAgentHealthChecker, - // new WorkspaceServiceLinksInjector(new MachineServiceLinksInjector()), - // true, - // false); - // } - // - // @Test - // public void shouldCreateWorkspace() throws Exception { - // final WorkspaceConfigDto configDto = createConfigDto(); - // final WorkspaceImpl workspace = createWorkspace(configDto); - // when(wsManager.createWorkspace(any(), any(), any())).thenReturn(workspace); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .contentType("application/json") - // .body(configDto) - // .when() - // .post(SECURE_PATH + "/workspace" + - // "?namespace=test" + - // "&attribute=stackId:stack123" + - // "&attribute=factoryId:factory123" + - // "&attribute=custom:custom:value"); - // - // assertEquals(response.getStatusCode(), 201); - // assertEquals(new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class), TEST_ACCOUNT), workspace); - // verify(validator).validateConfig(any()); - // verify(validator).validateAttributes(any()); - // verify(wsManager).createWorkspace(anyObject(), - // eq("test"), - // eq(ImmutableMap.of("stackId", "stack123", - // "factoryId", "factory123", - // "custom", "custom:value"))); - // } - // - // @Test - // public void shouldUseUsernameAsNamespaceWhenCreatingWorkspaceWithoutSpecifiedNamespace() throws Exception { - // final WorkspaceConfigDto configDto = createConfigDto(); - // final WorkspaceImpl workspace = createWorkspace(configDto); - // when(wsManager.createWorkspace(any(), any(), any())).thenReturn(workspace); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .contentType("application/json") - // .body(configDto) - // .when() - // .post(SECURE_PATH + "/workspace" + - // "?attribute=stackId:stack123" + - // "&attribute=factoryId:factory123" + - // "&attribute=custom:custom:value"); - // - // assertEquals(response.getStatusCode(), 201); - // assertEquals(new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class), TEST_ACCOUNT), workspace); - // verify(validator).validateConfig(any()); - // verify(validator).validateAttributes(any()); - // verify(wsManager).createWorkspace(anyObject(), - // eq(NAMESPACE), - // eq(ImmutableMap.of("stackId", "stack123", - // "factoryId", "factory123", - // "custom", "custom:value"))); - // } - // - // @Test - // public void shouldStartTheWorkspaceAfterItIsCreatedWhenStartAfterCreateParamIsTrue() throws Exception { - // final WorkspaceConfigDto configDto = createConfigDto(); - // final WorkspaceImpl workspace = createWorkspace(configDto); - // when(wsManager.createWorkspace(any(), any(), any())).thenReturn(workspace); - // - // given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .contentType("application/json") - // .body(configDto) - // .when() - // .post(SECURE_PATH + "/workspace" + - // "?attribute=stackId:stack123" + - // "&attribute=factoryId:factory123" + - // "&attribute=custom:custom:value" + - // "&start-after-create=true"); - // - // verify(wsManager).startWorkspace(workspace.getId(), null, false); - // verify(wsManager).createWorkspace(anyObject(), - // anyString(), - // eq(ImmutableMap.of("stackId", "stack123", - // "factoryId", "factory123", - // "custom", "custom:value"))); - // } - // - // @Test - // public void createShouldReturn400WhenAttributesAreNotValid() throws Exception { - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .contentType("application/json") - // .body(createConfigDto()) - // .when() - // .post(SECURE_PATH + "/workspace?attribute=stackId=stack123"); - // - // assertEquals(response.getStatusCode(), 400); - // assertEquals(unwrapError(response), "Attribute 'stackId=stack123' is not valid, " + - // "it should contain name and value separated " + - // "with colon. For example: attributeName:attributeValue"); - // } - // - // @Test - // public void shouldRelativizeLinksOnCreateWorkspace() throws Exception { - // final String initialLocation = "http://localhost:8080/api/recipe/idrecipe123456789/script"; - // final WorkspaceConfigDto configDto = createConfigDto(); - // configDto.getEnvironments().get(configDto.getDefaultEnv()).getRecipe().withLocation(initialLocation) - // .withType("dockerfile"); - // - // ArgumentCaptor captor = ArgumentCaptor.forClass(WorkspaceConfigDto.class); - // when(wsManager.createWorkspace(captor.capture(), any(), any())).thenAnswer(invocation -> createWorkspace(captor.getValue())); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .contentType("application/json") - // .body(configDto) - // .when() - // .post(SECURE_PATH + "/workspace" + - // "?namespace=test" + - // "&attribute=stackId:stack123" + - // "&attribute=custom:custom:value"); - // - // assertEquals(response.getStatusCode(), 201); - // String savedLocation = unwrapDto(response, WorkspaceDto.class).getConfig() - // .getEnvironments() - // .get(configDto.getDefaultEnv()) - // .getRecipe() - // .getLocation(); - // - // assertEquals(savedLocation, initialLocation.substring(API_ENDPOINT.length())); - // } - // - // @Test - // public void createShouldReturn400WhenConfigIsNotSent() throws Exception { - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .contentType("application/json") - // .when() - // .post(SECURE_PATH + "/workspace?attribute=stackId=stack123"); - // - // assertEquals(response.getStatusCode(), 400); - // assertEquals(unwrapError(response), "Workspace configuration required"); - // } - // - // @Test - // public void shouldGetWorkspaceById() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .when() - // .get(SECURE_PATH + "/workspace/" + workspace.getId()); - // - // assertEquals(response.getStatusCode(), 200); - // assertEquals(new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class), TEST_ACCOUNT), workspace); - // } - // - // @Test - // public void shouldGetWorkspaces() throws Exception { - // final WorkspaceImpl workspace1 = createWorkspace(createConfigDto()); - // final WorkspaceImpl workspace2 = createWorkspace(createConfigDto(), STARTING); - // when(wsManager.getWorkspaces(USER_ID, false)).thenReturn(asList(workspace1, workspace2)); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .when() - // .get(SECURE_PATH + "/workspace"); - // - // assertEquals(response.getStatusCode(), 200); - // assertEquals(unwrapDtoList(response, WorkspaceDto.class).stream() - // .map(ws -> new WorkspaceImpl(ws, TEST_ACCOUNT)) - // .collect(toList()), - // asList(workspace1, workspace2)); - // } - // - // @Test - // public void shouldGetWorkspacesByNamespace() throws Exception { - // final WorkspaceImpl workspace1 = createWorkspace(createConfigDto()); - // final WorkspaceImpl workspace2 = createWorkspace(createConfigDto(), STARTING); - // when(wsManager.getByNamespace(NAMESPACE, false)).thenReturn(asList(workspace1, workspace2)); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .when() - // .get(SECURE_PATH + "/workspace/namespace/" + NAMESPACE); - // - // assertEquals(response.getStatusCode(), 200); - // assertEquals(unwrapDtoList(response, WorkspaceDto.class).stream() - // .map(ws -> new WorkspaceImpl(ws, TEST_ACCOUNT)) - // .collect(toList()), - // asList(workspace1, workspace2)); - // } - // - // @Test - // public void shouldGetWorkspacesByStatus() throws Exception { - // final WorkspaceImpl workspace1 = createWorkspace(createConfigDto()); - // final WorkspaceImpl workspace2 = createWorkspace(createConfigDto(), STARTING); - // when(wsManager.getWorkspaces(USER_ID, false)).thenReturn(asList(workspace1, workspace2)); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .when() - // .get(SECURE_PATH + "/workspace?status=starting"); - // - // assertEquals(response.getStatusCode(), 200); - // assertEquals(unwrapDtoList(response, WorkspaceDto.class).stream() - // .map(ws -> new WorkspaceImpl(ws, TEST_ACCOUNT)) - // .collect(toList()), - // singletonList(workspace2)); - // } - // - // @Test - // public void shouldUpdateTheWorkspace() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // when(wsManager.updateWorkspace(any(), any())).thenReturn(workspace); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // final WorkspaceDto workspaceDto = DtoConverter.asDto(workspace); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .contentType("application/json") - // .body(workspaceDto) - // .when() - // .put(SECURE_PATH + "/workspace/" + workspace.getId()); - // - // assertEquals(response.getStatusCode(), 200); - // assertEquals(new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class), TEST_ACCOUNT), workspace); - // verify(validator).validateWorkspace(any()); - // } - // - // @Test - // public void shouldDeleteWorkspace() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // when(wsManager.getSnapshot(anyString())).thenReturn(ImmutableList.of(mock(SnapshotImpl.class))); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .when() - // .delete(SECURE_PATH + "/workspace/" + workspace.getId()); - // - // assertEquals(response.getStatusCode(), 204); - // verify(wsManager).removeSnapshots(workspace.getId()); - // verify(wsManager).removeWorkspace(workspace.getId()); - // } - // - // @Test - // public void shouldStartWorkspace() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // when(wsManager.startWorkspace(any(), any(), any())).thenReturn(workspace); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .when() - // .post(SECURE_PATH + "/workspace/" + workspace.getId() + "/runtime" + - // "?environment=" + workspace.getConfig().getDefaultEnv()); - // - // assertEquals(response.getStatusCode(), 200); - // assertEquals(new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class), TEST_ACCOUNT), workspace); - // verify(wsManager).startWorkspace(workspace.getId(), workspace.getConfig().getDefaultEnv(), null); - // } - // - // @Test - // public void shouldRestoreWorkspace() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // when(wsManager.startWorkspace(any(), any(), any())).thenReturn(workspace); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .when() - // .post(SECURE_PATH + "/workspace/" + workspace.getId() + "/runtime" + - // "?environment=" + workspace.getConfig().getDefaultEnv() + "&restore=true"); - // - // assertEquals(response.getStatusCode(), 200); - // assertEquals(new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class), TEST_ACCOUNT), workspace); - // verify(wsManager).startWorkspace(workspace.getId(), workspace.getConfig().getDefaultEnv(), true); - // } - // - // @Test - // public void shouldNotRestoreWorkspace() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // when(wsManager.startWorkspace(any(), any(), any())).thenReturn(workspace); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .when() - // .post(SECURE_PATH + "/workspace/" + workspace.getId() + "/runtime" + - // "?environment=" + workspace.getConfig().getDefaultEnv() + "&restore=false"); - // - // assertEquals(response.getStatusCode(), 200); - // assertEquals(new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class), TEST_ACCOUNT), workspace); - // verify(wsManager).startWorkspace(workspace.getId(), workspace.getConfig().getDefaultEnv(), false); - // } - // - // @Test - // public void shouldStartWorkspaceFromConfig() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // when(wsManager.startWorkspace(anyObject(), - // anyString(), - // anyBoolean())).thenReturn(workspace); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // final WorkspaceDto workspaceDto = DtoConverter.asDto(workspace); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .contentType("application/json") - // .body(workspaceDto.getConfig()) - // .when() - // .post(SECURE_PATH + "/workspace/runtime" + - // "?namespace=test" + - // "&temporary=true"); - // - // assertEquals(response.getStatusCode(), 200); - // verify(validator).validateConfig(any()); - // verify(wsManager).startWorkspace(any(), - // eq("test"), - // eq(true)); - // } - // - // @Test - // public void shouldUseUsernameAsNamespaceWhenStartingWorkspaceFromConfigWithoutNamespace() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // when(wsManager.startWorkspace(anyObject(), - // anyString(), - // anyBoolean())).thenReturn(workspace); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // final WorkspaceDto workspaceDto = DtoConverter.asDto(workspace); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .contentType("application/json") - // .body(workspaceDto.getConfig()) - // .when() - // .post(SECURE_PATH + "/workspace/runtime" + - // "?temporary=true"); - // - // assertEquals(response.getStatusCode(), 200); - // verify(validator).validateConfig(any()); - // verify(wsManager).startWorkspace(any(), - // eq(NAMESPACE), - // eq(true)); - // } - // - // @Test - // public void shouldStopWorkspace() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .when() - // .delete(SECURE_PATH + "/workspace/" + workspace.getId() + "/runtime"); - // - // assertEquals(response.getStatusCode(), 204); - // verify(wsManager).stopWorkspace(workspace.getId(), null); - // } - // - // @Test - // public void shouldCreateSnapshot() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .when() - // .post(SECURE_PATH + "/workspace/" + workspace.getId() + "/snapshot"); - // - // assertEquals(response.getStatusCode(), 204); - // verify(wsManager).createSnapshot(workspace.getId()); - // } - // - // @Test - // public void shouldAddCommand() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // when(wsManager.updateWorkspace(any(), any())).thenReturn(workspace); - // final CommandDto commandDto = createCommandDto(); - // final int commandsSizeBefore = workspace.getConfig().getCommands().size(); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .contentType("application/json") - // .body(commandDto) - // .when() - // .post(SECURE_PATH + "/workspace/" + workspace.getId() + "/command"); - // - // assertEquals(response.getStatusCode(), 200); - // assertEquals(new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class), TEST_ACCOUNT) - // .getConfig() - // .getCommands() - // .size(), commandsSizeBefore + 1); - // verify(validator).validateConfig(workspace.getConfig()); - // verify(wsManager).updateWorkspace(any(), any()); - // } - // - // @Test - // public void shouldUpdateCommand() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // when(wsManager.updateWorkspace(any(), any())).thenReturn(workspace); - // final CommandDto commandDto = createCommandDto(); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .contentType("application/json") - // .body(commandDto) - // .when() - // .put(SECURE_PATH + "/workspace/" + workspace.getId() + "/command/" + commandDto.getName()); - // - // assertEquals(response.getStatusCode(), 200); - // verify(validator).validateConfig(workspace.getConfig()); - // verify(wsManager).updateWorkspace(any(), any()); - // } - // - // @Test - // public void shouldRespond404WhenUpdatingCommandWhichDoesNotExist() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .contentType("application/json") - // .body(createCommandDto()) - // .when() - // .put(SECURE_PATH + "/workspace/" + workspace.getId() + "/command/fake"); - // - // assertEquals(response.getStatusCode(), 404); - // assertEquals(unwrapError(response), "Workspace '" + workspace.getId() + "' doesn't contain command 'fake'"); - // verify(wsManager, never()).updateWorkspace(any(), any()); - // } - // - // @Test - // public void shouldDeleteCommand() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // final int commandsSizeBefore = workspace.getConfig().getCommands().size(); - // final CommandImpl firstCommand = workspace.getConfig().getCommands().iterator().next(); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .when() - // .delete(SECURE_PATH + "/workspace/" + workspace.getId() - // + "/command/" + firstCommand.getName()); - // - // assertEquals(response.getStatusCode(), 204); - // assertEquals(workspace.getConfig().getCommands().size(), commandsSizeBefore - 1); - // verify(wsManager).updateWorkspace(any(), any()); - // } - // - // @Test - // public void shouldAddEnvironment() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // when(wsManager.updateWorkspace(any(), any())).thenReturn(workspace); - // final EnvironmentDto envDto = createEnvDto(); - // final int envsSizeBefore = workspace.getConfig().getEnvironments().size(); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .contentType("application/json") - // .body(envDto) - // .when() - // .queryParam("name", "new-env") - // .post(SECURE_PATH + "/workspace/" + workspace.getId() + "/environment"); - // - // assertEquals(response.getStatusCode(), 200); - // assertEquals(new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class), TEST_ACCOUNT) - // .getConfig() - // .getEnvironments() - // .size(), envsSizeBefore + 1); - // verify(validator).validateConfig(workspace.getConfig()); - // verify(wsManager).updateWorkspace(any(), any()); - // } - // - // @Test - // public void shouldUpdateEnvironment() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // when(wsManager.updateWorkspace(any(), any())).thenReturn(workspace); - // final EnvironmentDto envDto = createEnvDto(); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .contentType("application/json") - // .body(envDto) - // .when() - // .put(SECURE_PATH + "/workspace/" + workspace.getId() - // + "/environment/" + workspace.getConfig().getDefaultEnv()); - // - // assertEquals(response.getStatusCode(), 200); - // assertEquals(workspace.getConfig().getEnvironments().size(), 1); - // verify(validator).validateConfig(workspace.getConfig()); - // verify(wsManager).updateWorkspace(any(), any()); - // } - // - // @Test - // public void shouldRespond404WhenUpdatingEnvironmentWhichDoesNotExist() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .contentType("application/json") - // .body(createEnvDto()) - // .when() - // .put(SECURE_PATH + "/workspace/" + workspace.getId() + "/environment/fake"); - // - // assertEquals(response.getStatusCode(), 404); - // assertEquals(unwrapError(response), "Workspace '" + workspace.getId() + "' doesn't contain environment 'fake'"); - // verify(wsManager, never()).updateWorkspace(any(), any()); - // } - // - // @Test - // public void shouldDeleteEnvironment() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // Map.Entry envEntry = - // workspace.getConfig().getEnvironments().entrySet().iterator().next(); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .when() - // .delete(SECURE_PATH + "/workspace/" + workspace.getId() - // + "/environment/" + envEntry.getKey()); - // - // assertEquals(response.getStatusCode(), 204); - // verify(wsManager).updateWorkspace(any(), any()); - // } - // - // - // @Test - // public void shouldRelativizeLinksOnAddEnvironment() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // final String initialLocation = "http://localhost:8080/api/recipe/idrecipe123456789/script"; - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // when(wsManager.updateWorkspace(any(), any())).thenReturn(workspace); - // final EnvironmentDto envDto = createEnvDto(); - // envDto.getRecipe().withLocation(initialLocation).withType("dockerfile"); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .contentType("application/json") - // .body(envDto) - // .when() - // .queryParam("name", "new-env") - // .post(SECURE_PATH + "/workspace/" + workspace.getId() + "/environment"); - // - // assertEquals(response.getStatusCode(), 200); - // String savedLocation = unwrapDto(response, WorkspaceDto.class).getConfig() - // .getEnvironments() - // .get("new-env") - // .getRecipe() - // .getLocation(); - // - // assertEquals(savedLocation, initialLocation.substring(API_ENDPOINT.length())); - // } - // - // - // @Test - // public void shouldAddProject() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // when(wsManager.updateWorkspace(any(), any())).thenReturn(workspace); - // final ProjectConfigDto projectDto = createProjectDto(); - // final int projectsSizeBefore = workspace.getConfig().getProjects().size(); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .contentType("application/json") - // .body(projectDto) - // .when() - // .post(SECURE_PATH + "/workspace/" + workspace.getId() + "/project"); - // - // assertEquals(response.getStatusCode(), 200); - // assertEquals(new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class), TEST_ACCOUNT) - // .getConfig() - // .getProjects() - // .size(), projectsSizeBefore + 1); - // verify(validator).validateConfig(workspace.getConfig()); - // verify(wsManager).updateWorkspace(any(), any()); - // } - // - // @Test - // public void shouldUpdateProject() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // when(wsManager.updateWorkspace(any(), any())).thenReturn(workspace); - // final ProjectConfigDto projectDto = createProjectDto(); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .contentType("application/json") - // .body(projectDto) - // .when() - // .put(SECURE_PATH + "/workspace/" + workspace.getId() - // + "/project" + projectDto.getPath()); - // - // assertEquals(response.getStatusCode(), 200); - // verify(validator).validateConfig(workspace.getConfig()); - // verify(wsManager).updateWorkspace(any(), any()); - // } - // - // @Test - // public void shouldRespond404WhenUpdatingProjectWhichDoesNotExist() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .contentType("application/json") - // .body(createProjectDto()) - // .when() - // .put(SECURE_PATH + "/workspace/" + workspace.getId() + "/project/fake"); - // - // assertEquals(response.getStatusCode(), 404); - // assertEquals(unwrapError(response), "Workspace '" + workspace.getId() + "' doesn't contain project with path '/fake'"); - // verify(wsManager, never()).updateWorkspace(any(), any()); - // } - // - // @Test - // public void shouldDeleteProject() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // final ProjectConfig firstProject = workspace.getConfig().getProjects().iterator().next(); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .when() - // .delete(SECURE_PATH + "/workspace/" + workspace.getId() - // + "/project" + firstProject.getPath()); - // - // assertEquals(response.getStatusCode(), 204); - // verify(wsManager).updateWorkspace(any(), any()); - // } - // - // @Test - // public void testWorkspaceLinks() throws Exception { - // // given - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // EnvironmentImpl environment = workspace.getConfig() - // .getEnvironments() - // .get(workspace.getConfig().getDefaultEnv()); - // assertNotNull(environment); - // - // final RuntimeImpl runtime = new RuntimeImpl(workspace.getConfig().getDefaultEnv()); - // OldMachineConfigImpl devMachineConfig = OldMachineConfigImpl.builder() - // .setDev(true) - // .setEnvVariables(emptyMap()) - // .setServers(emptyList()) - // .setLimits(new MachineLimitsImpl(1024)) - // .setSource(new MachineSourceImpl("type").setContent("content")) - // .setName(environment.getMachines() - // .keySet() - // .iterator() - // .next()) - // .setType("type") - // .build(); - // runtime.setDevMachine(new OldMachineImpl(devMachineConfig, - // "machine123", - // workspace.getId(), - // workspace.getConfig().getDefaultEnv(), - // USER_ID, - // MachineStatus.RUNNING, - // new MachineImpl(emptyMap(), - // emptyMap(), - // singletonMap("8080/https", - // new OldServerImpl( - // "wsagent", - // "https", - // "address", - // "url", - // new ServerPropertiesImpl( - // "path", - // "internaladdress", - // "internalurl")))))); - // runtime.getMachines().add(runtime.getDevMachine()); - // workspace.setStatus(RUNNING); - // workspace.setRuntime(runtime); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // - // // when - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .when() - // .get(SECURE_PATH + "/workspace/" + workspace.getId()); - // - // // then - // assertEquals(response.getStatusCode(), 200); - // final WorkspaceDto workspaceDto = unwrapDto(response, WorkspaceDto.class); - // final Set actualRels = workspaceDto.getLinks() - // .stream() - // .map(Link::getRel) - // .collect(toSet()); - // final Set expectedRels = new HashSet<>(asList(LINK_REL_START_WORKSPACE, - // LINK_REL_REMOVE_WORKSPACE, - // GET_ALL_USER_WORKSPACES, - // LINK_REL_GET_SNAPSHOT, - // LINK_REL_GET_WORKSPACE_EVENTS_CHANNEL, - // LINK_REL_IDE_URL, - // LINK_REL_SELF, - // LINK_REL_ENVIRONMENT_OUTPUT_CHANNEL, - // LINK_REL_ENVIRONMENT_STATUS_CHANNEL)); - // assertTrue(actualRels.equals(expectedRels), format("Links difference: '%s'. \n" + - // "Returned links: '%s', \n" + - // "Expected links: '%s'.", - // Sets.symmetricDifference(actualRels, expectedRels), - // actualRels.toString(), - // expectedRels.toString())); - // assertNotNull(workspaceDto.getRuntime().getLink(LINK_REL_STOP_WORKSPACE), "Runtime doesn't contain stop link"); - // assertNotNull(workspaceDto.getRuntime().getLink(WSAGENT_REFERENCE), "Runtime doesn't contain wsagent link"); - // assertNotNull(workspaceDto.getRuntime().getLink(WSAGENT_WEBSOCKET_REFERENCE), "Runtime doesn't contain wsagent.websocket link"); - // } - // - // @Test - // public void shouldReturnSnapshotsOnGetSnapshot() throws Exception { - // // given - // String workspaceId = "testWsId1"; - // SnapshotImpl.SnapshotBuilder snapshotBuilder = SnapshotImpl.builder() - // .setCreationDate(System.currentTimeMillis()) - // .setDescription("description") - // .setDev(true) - // .setEnvName("envName") - // .setId("snap1") - // .setMachineName("machine1") - // .setMachineSource(new MachineSourceImpl("type") - // .setContent("content")) - // .setType("type") - // .setWorkspaceId(workspaceId); - // SnapshotImpl snapshot1 = snapshotBuilder.build(); - // SnapshotImpl snapshot2 = snapshotBuilder.setDev(false).build(); - // - // List originSnapshots = Arrays.asList(snapshot1, snapshot2); - // when(wsManager.getSnapshot(workspaceId)).thenReturn(originSnapshots); - // - // // when - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .when() - // .get(SECURE_PATH + "/workspace/" + workspaceId + "/snapshot"); - // - // // then - // assertEquals(response.getStatusCode(), 200); - // List snapshotDtos = unwrapDtoList(response, SnapshotDto.class); - // List newSnapshots = snapshotDtos.stream().map(SnapshotImpl::new).collect(Collectors.toList()); - // originSnapshots.forEach(snapshot -> snapshot.setMachineSource(null)); - // assertEquals(newSnapshots, originSnapshots); - // verify(wsManager).getSnapshot(workspaceId); - // } - // - // @Test - // public void stateOfWsAgentShouldBeChecked() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // workspace.setStatus(RUNNING); - // - // WsAgentHealthStateDto wsAgentState = newDto(WsAgentHealthStateDto.class); - // RuntimeImpl runtime = mock(RuntimeImpl.class); - // OldMachineImpl machine = mock(OldMachineImpl.class); - // when(runtime.getDevMachine()).thenReturn(machine); - // when(wsAgentHealthChecker.check(machine)).thenReturn(wsAgentState); - // - // workspace.setRuntime(runtime); - // - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .when() - // .get(SECURE_PATH + "/workspace/" + workspace.getId() + "/check"); - // - // verify(wsAgentHealthChecker).check(machine); - // assertEquals(RUNNING, wsAgentState.getWorkspaceStatus()); - // assertEquals(200, response.getStatusCode()); - // } - // - // @Test - // public void stateOfWsAgentShouldNotBeCheckedIfWsIsNotRunning() throws Exception { - // final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - // workspace.setStatus(STARTING); - // when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - // - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .when() - // .get(SECURE_PATH + "/workspace/" + workspace.getId() + "/check"); - // - // verify(wsAgentHealthChecker, never()).check(any()); - // assertEquals(200, response.getStatusCode()); - // } - // - // @Test - // public void shouldReturnEmptyListIfNotSnapshotsFound() throws Exception { - // // given - // String workspaceId = "testWsId1"; - // - // when(wsManager.getSnapshot(workspaceId)).thenReturn(Collections.emptyList()); - // - // // when - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .when() - // .get(SECURE_PATH + "/workspace/" + workspaceId + "/snapshot"); - // - // // then - // assertEquals(response.getStatusCode(), 200); - // List snapshotDtos = unwrapDtoList(response, SnapshotDto.class); - // assertTrue(snapshotDtos.isEmpty()); - // verify(wsManager).getSnapshot(workspaceId); - // } - // - // @Test - // public void shouldBeAbleToGetSettings() throws Exception { - // final Response response = given().auth() - // .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - // .when() - // .get(SECURE_PATH + "/workspace/settings"); - // - // assertEquals(response.getStatusCode(), 200); - // final Map settings = new Gson().fromJson(response.print(), - // new TypeToken>() {}.getType()); - // assertEquals(settings, ImmutableMap.of("che.workspace.auto_snapshot", "true", - // "che.workspace.auto_restore", "false")); - // } - // - // private static String unwrapError(Response response) { - // return unwrapDto(response, ServiceError.class).getMessage(); - // } - // - // private static T unwrapDto(Response response, Class dtoClass) { - // return DtoFactory.getInstance().createDtoFromJson(response.body().print(), dtoClass); - // } - // - // private static List unwrapDtoList(Response response, Class dtoClass) { - // return DtoFactory.getInstance().createListDtoFromJson(response.body().print(), dtoClass) - // .stream() - // .collect(toList()); - // } - // - // private static WorkspaceImpl createWorkspace(WorkspaceConfig configDto, WorkspaceStatus status) { - // return WorkspaceImpl.builder() - // .setConfig(configDto) - // .generateId() - // .setAccount(TEST_ACCOUNT) - // .setStatus(status) - // .build(); - // } - // - // private static WorkspaceImpl createWorkspace(WorkspaceConfig configDto) { - // return createWorkspace(configDto, WorkspaceStatus.STOPPED); - // } - // - // private static CommandDto createCommandDto() { - // return DtoConverter.asDto(new CommandImpl("MCI", "mvn clean install", "maven")); - // } - // - // private static ProjectConfigDto createProjectDto() { - // return newDto(ProjectConfigDto.class).withName("project-name") - // .withPath("/project/path") - // .withDescription("Test project") - // .withMixins(new ArrayList<>(singleton("maven"))) - // .withSource(newDto(SourceStorageDto.class).withLocation("location") - // .withType("type")) - // .withAttributes(new HashMap<>()); - // - // } - // - // private static EnvironmentDto createEnvDto() { - // MachineConfigImpl devMachine = new MachineConfigImpl(singletonList("org.eclipse.che.ws-agent"), - // null, - // singletonMap("memoryLimitBytes", "10000")); - // - // return DtoConverter.asDto(new EnvironmentImpl(new RecipeImpl("type", "content-type", "content", null), - // singletonMap("dev-machine", devMachine))); - // } - // - // private static WorkspaceConfigDto createConfigDto() { - // final WorkspaceConfigImpl config = WorkspaceConfigImpl.builder() - // .setName("dev-workspace") - // .setDefaultEnv("dev-env") - // .setEnvironments(singletonMap("dev-env", new EnvironmentImpl(createEnvDto()))) - // .setCommands(singletonList(createCommandDto())) - // .setProjects(singletonList(createProjectDto())) - // .build(); - // return DtoConverter.asDto(config); - // } - // - // @Filter - // public static class EnvironmentFilter implements RequestFilter { - // - // public void doFilter(GenericContainerRequest request) { - // EnvironmentContext.getCurrent().setSubject(new SubjectImpl(NAMESPACE, USER_ID, "token", false)); - // } - // } + @SuppressWarnings("unused") + private static final ApiExceptionMapper MAPPER = new ApiExceptionMapper(); + + private static final String NAMESPACE = "user"; + private static final String USER_ID = "user123"; + private static final String API_ENDPOINT = "http://localhost:8080/api"; + private static final Account TEST_ACCOUNT = new AccountImpl("anyId", NAMESPACE, "test"); + + @SuppressWarnings("unused") + private static final EnvironmentFilter FILTER = new EnvironmentFilter(); + + @Mock private WorkspaceManager wsManager; + @Mock private MachineTokenProvider machineTokenProvider; + @Mock private WorkspaceLinksGenerator linksGenerator; + + private WorkspaceService service; + + @BeforeMethod + public void setup() { + service = new WorkspaceService(API_ENDPOINT, wsManager, machineTokenProvider, linksGenerator); + } + + @Test + public void shouldCreateWorkspace() throws Exception { + final WorkspaceConfigDto configDto = createConfigDto(); + final WorkspaceImpl workspace = createWorkspace(configDto); + when(wsManager.createWorkspace(any(), anyString(), any())).thenReturn(workspace); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .contentType("application/json") + .body(configDto) + .when() + .post( + SECURE_PATH + + "/workspace" + + "?namespace=test" + + "&attribute=stackId:stack123" + + "&attribute=factoryId:factory123" + + "&attribute=custom:custom:value"); + + assertEquals(response.getStatusCode(), 201); + assertEquals( + new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class), TEST_ACCOUNT), workspace); + verify(wsManager) + .createWorkspace( + anyObject(), + eq("test"), + eq( + ImmutableMap.of( + "stackId", "stack123", + "factoryId", "factory123", + "custom", "custom:value"))); + } + + @Test + public void shouldUseUsernameAsNamespaceWhenCreatingWorkspaceWithoutSpecifiedNamespace() + throws Exception { + final WorkspaceConfigDto configDto = createConfigDto(); + final WorkspaceImpl workspace = createWorkspace(configDto); + when(wsManager.createWorkspace(any(WorkspaceConfig.class), anyString(), any())) + .thenReturn(workspace); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .contentType("application/json") + .body(configDto) + .when() + .post( + SECURE_PATH + + "/workspace" + + "?attribute=stackId:stack123" + + "&attribute=factoryId:factory123" + + "&attribute=custom:custom:value"); + + assertEquals(response.getStatusCode(), 201); + assertEquals( + new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class), TEST_ACCOUNT), workspace); + verify(wsManager) + .createWorkspace( + anyObject(), + eq(NAMESPACE), + eq( + ImmutableMap.of( + "stackId", "stack123", + "factoryId", "factory123", + "custom", "custom:value"))); + } + + @Test + public void shouldStartTheWorkspaceAfterItIsCreatedWhenStartAfterCreateParamIsTrue() + throws Exception { + final WorkspaceConfigDto configDto = createConfigDto(); + final WorkspaceImpl workspace = createWorkspace(configDto); + when(wsManager.createWorkspace(any(), any(), any())).thenReturn(workspace); + + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .contentType("application/json") + .body(configDto) + .when() + .post( + SECURE_PATH + + "/workspace" + + "?attribute=stackId:stack123" + + "&attribute=factoryId:factory123" + + "&attribute=custom:custom:value" + + "&start-after-create=true"); + + verify(wsManager).startWorkspace(workspace.getId(), null, emptyMap()); + verify(wsManager) + .createWorkspace( + anyObject(), + anyString(), + eq( + ImmutableMap.of( + "stackId", "stack123", + "factoryId", "factory123", + "custom", "custom:value"))); + } + + @Test + public void createShouldReturn400WhenAttributesAreNotValid() throws Exception { + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .contentType("application/json") + .body(createConfigDto()) + .when() + .post(SECURE_PATH + "/workspace?attribute=stackId=stack123"); + + assertEquals(response.getStatusCode(), 400); + assertEquals( + unwrapError(response), + "Attribute 'stackId=stack123' is not valid, " + + "it should contain name and value separated " + + "with colon. For example: attributeName:attributeValue"); + } + + @Test + public void shouldRelativizeLinksOnCreateWorkspace() throws Exception { + final String initialLocation = "http://localhost:8080/api/recipe/idrecipe123456789/script"; + final WorkspaceConfigDto configDto = createConfigDto(); + configDto + .getEnvironments() + .get(configDto.getDefaultEnv()) + .getRecipe() + .withLocation(initialLocation) + .withType("dockerfile"); + + ArgumentCaptor captor = ArgumentCaptor.forClass(WorkspaceConfigDto.class); + when(wsManager.createWorkspace(captor.capture(), any(), any())) + .thenAnswer(invocation -> createWorkspace(captor.getValue())); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .contentType("application/json") + .body(configDto) + .when() + .post( + SECURE_PATH + + "/workspace" + + "?namespace=test" + + "&attribute=stackId:stack123" + + "&attribute=custom:custom:value"); + + assertEquals(response.getStatusCode(), 201); + String savedLocation = + unwrapDto(response, WorkspaceDto.class) + .getConfig() + .getEnvironments() + .get(configDto.getDefaultEnv()) + .getRecipe() + .getLocation(); + + assertEquals(savedLocation, initialLocation.substring(API_ENDPOINT.length())); + } + + @Test + public void createShouldReturn400WhenConfigIsNotSent() throws Exception { + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .contentType("application/json") + .when() + .post(SECURE_PATH + "/workspace?attribute=stackId=stack123"); + + assertEquals(response.getStatusCode(), 400); + assertEquals(unwrapError(response), "Workspace configuration required"); + } + + @Test(dataProvider = "validWorkspaceKeys") + public void shouldGetWorkspaceByKey(String key) throws Exception { + final WorkspaceImpl workspace = createWorkspace(createConfigDto()); + when(wsManager.getWorkspace(key)).thenReturn(workspace); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .when() + .get(SECURE_PATH + "/workspace/" + key); + + assertEquals(response.getStatusCode(), 200); + assertEquals( + new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class), TEST_ACCOUNT), workspace); + verify(machineTokenProvider, never()).getToken(workspace.getId()); + } + + @DataProvider + public Object[][] validWorkspaceKeys() { + return new Object[][] {{"workspaceId"}, {"namespace:name"}, {":name"}}; + } + + @Test + public void shouldReturnWorkspaceWithTokenIfRuntimeExists() throws Exception { + final WorkspaceImpl workspace = createWorkspace(createConfigDto()); + workspace.setRuntime(new RuntimeImpl("activeEnv", emptyMap(), "user123")); + when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); + when(machineTokenProvider.getToken(anyString())).thenReturn("superToken"); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .when() + .get(SECURE_PATH + "/workspace/" + workspace.getId()); + + assertEquals(response.getStatusCode(), 200); + WorkspaceDto retrievedWorkspace = unwrapDto(response, WorkspaceDto.class); + assertEquals(retrievedWorkspace.getRuntime().getUserToken(), "superToken"); + verify(machineTokenProvider).getToken(workspace.getId()); + } + + @Test(dataProvider = "invalidWorkspaceKeys") + public void getWorkspaceByKeyShouldReturn400WhenKeyIsInvalid(String workspaceKey) + throws Exception { + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .when() + .get(SECURE_PATH + "/workspace/" + workspaceKey); + + assertEquals(response.getStatusCode(), 400); + } + + @DataProvider + public Object[][] invalidWorkspaceKeys() { + return new Object[][] {{"first:second:third"}, {"namespace:"}}; + } + + @Test + public void shouldGetWorkspaces() throws Exception { + final WorkspaceImpl workspace1 = createWorkspace(createConfigDto()); + final WorkspaceImpl workspace2 = createWorkspace(createConfigDto(), STARTING); + when(wsManager.getWorkspaces(USER_ID, false)).thenReturn(asList(workspace1, workspace2)); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .when() + .get(SECURE_PATH + "/workspace"); + + assertEquals(response.getStatusCode(), 200); + assertEquals( + unwrapDtoList(response, WorkspaceDto.class) + .stream() + .map(ws -> new WorkspaceImpl(ws, TEST_ACCOUNT)) + .collect(toList()), + asList(workspace1, workspace2)); + } + + @Test + public void shouldGetWorkspacesByNamespace() throws Exception { + final WorkspaceImpl workspace1 = createWorkspace(createConfigDto()); + final WorkspaceImpl workspace2 = createWorkspace(createConfigDto(), STARTING); + when(wsManager.getByNamespace(NAMESPACE, false)).thenReturn(asList(workspace1, workspace2)); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .when() + .get(SECURE_PATH + "/workspace/namespace/" + NAMESPACE); + + assertEquals(response.getStatusCode(), 200); + assertEquals( + unwrapDtoList(response, WorkspaceDto.class) + .stream() + .map(ws -> new WorkspaceImpl(ws, TEST_ACCOUNT)) + .collect(toList()), + asList(workspace1, workspace2)); + } + + @Test + public void shouldGetWorkspacesByStatus() throws Exception { + final WorkspaceImpl workspace1 = createWorkspace(createConfigDto()); + final WorkspaceImpl workspace2 = createWorkspace(createConfigDto(), STARTING); + when(wsManager.getWorkspaces(USER_ID, false)).thenReturn(asList(workspace1, workspace2)); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .when() + .get(SECURE_PATH + "/workspace?status=starting"); + + assertEquals(response.getStatusCode(), 200); + assertEquals( + unwrapDtoList(response, WorkspaceDto.class) + .stream() + .map(ws -> new WorkspaceImpl(ws, TEST_ACCOUNT)) + .collect(toList()), + singletonList(workspace2)); + } + + @Test + public void shouldUpdateTheWorkspace() throws Exception { + final WorkspaceImpl workspace = createWorkspace(createConfigDto()); + when(wsManager.updateWorkspace(any(), any())).thenReturn(workspace); + when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); + final WorkspaceDto workspaceDto = DtoConverter.asDto(workspace); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .contentType("application/json") + .body(workspaceDto) + .when() + .put(SECURE_PATH + "/workspace/" + workspace.getId()); + + assertEquals(response.getStatusCode(), 200); + assertEquals( + new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class), TEST_ACCOUNT), workspace); + } + + @Test + public void shouldDeleteWorkspace() throws Exception { + final WorkspaceImpl workspace = createWorkspace(createConfigDto()); + + when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .when() + .delete(SECURE_PATH + "/workspace/" + workspace.getId()); + + assertEquals(response.getStatusCode(), 204); + verify(wsManager).removeWorkspace(workspace.getId()); + } + + @Test + public void shouldStartWorkspace() throws Exception { + final WorkspaceImpl workspace = createWorkspace(createConfigDto()); + when(wsManager.startWorkspace(any(), any(), any())).thenReturn(workspace); + when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .when() + .post( + SECURE_PATH + + "/workspace/" + + workspace.getId() + + "/runtime" + + "?environment=" + + workspace.getConfig().getDefaultEnv()); + + assertEquals(response.getStatusCode(), 200); + assertEquals( + new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class), TEST_ACCOUNT), workspace); + verify(wsManager) + .startWorkspace(workspace.getId(), workspace.getConfig().getDefaultEnv(), emptyMap()); + } + + @Test + public void shouldStartWorkspaceFromConfig() throws Exception { + final WorkspaceImpl workspace = createWorkspace(createConfigDto()); + when(wsManager.startWorkspace(anyObject(), anyString(), anyBoolean(), any())) + .thenReturn(workspace); + when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); + final WorkspaceDto workspaceDto = DtoConverter.asDto(workspace); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .contentType("application/json") + .body(workspaceDto.getConfig()) + .when() + .post(SECURE_PATH + "/workspace/runtime" + "?namespace=test" + "&temporary=true"); + + assertEquals(response.getStatusCode(), 200); + verify(wsManager).startWorkspace(any(), eq("test"), eq(true), eq(emptyMap())); + } + + @Test + public void shouldUseUsernameAsNamespaceWhenStartingWorkspaceFromConfigWithoutNamespace() + throws Exception { + final WorkspaceImpl workspace = createWorkspace(createConfigDto()); + when(wsManager.startWorkspace(anyObject(), anyString(), anyBoolean(), any())) + .thenReturn(workspace); + when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); + final WorkspaceDto workspaceDto = DtoConverter.asDto(workspace); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .contentType("application/json") + .body(workspaceDto.getConfig()) + .when() + .post(SECURE_PATH + "/workspace/runtime" + "?temporary=true"); + + assertEquals(response.getStatusCode(), 200); + verify(wsManager).startWorkspace(any(), eq(NAMESPACE), eq(true), eq(emptyMap())); + } + + @Test + public void shouldStopWorkspace() throws Exception { + final WorkspaceImpl workspace = createWorkspace(createConfigDto()); + when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .when() + .delete(SECURE_PATH + "/workspace/" + workspace.getId() + "/runtime"); + + assertEquals(response.getStatusCode(), 204); + verify(wsManager).stopWorkspace(workspace.getId(), emptyMap()); + } + + @Test + public void shouldAddCommand() throws Exception { + final WorkspaceImpl workspace = createWorkspace(createConfigDto()); + when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); + when(wsManager.updateWorkspace(any(), any())).thenReturn(workspace); + final CommandDto commandDto = createCommandDto(); + final int commandsSizeBefore = workspace.getConfig().getCommands().size(); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .contentType("application/json") + .body(commandDto) + .when() + .post(SECURE_PATH + "/workspace/" + workspace.getId() + "/command"); + + assertEquals(response.getStatusCode(), 200); + assertEquals( + new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class), TEST_ACCOUNT) + .getConfig() + .getCommands() + .size(), + commandsSizeBefore + 1); + verify(wsManager).updateWorkspace(any(), any()); + } + + @Test + public void shouldUpdateCommand() throws Exception { + final WorkspaceImpl workspace = createWorkspace(createConfigDto()); + when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); + when(wsManager.updateWorkspace(any(), any())).thenReturn(workspace); + final CommandDto commandDto = createCommandDto(); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .contentType("application/json") + .body(commandDto) + .when() + .put( + SECURE_PATH + + "/workspace/" + + workspace.getId() + + "/command/" + + commandDto.getName()); + + assertEquals(response.getStatusCode(), 200); + verify(wsManager).updateWorkspace(any(), any()); + } + + @Test + public void shouldRespond404WhenUpdatingCommandWhichDoesNotExist() throws Exception { + final WorkspaceImpl workspace = createWorkspace(createConfigDto()); + when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .contentType("application/json") + .body(createCommandDto()) + .when() + .put(SECURE_PATH + "/workspace/" + workspace.getId() + "/command/fake"); + + assertEquals(response.getStatusCode(), 404); + assertEquals( + unwrapError(response), + "Workspace '" + workspace.getId() + "' doesn't contain command 'fake'"); + verify(wsManager, never()).updateWorkspace(any(), any()); + } + + @Test + public void shouldDeleteCommand() throws Exception { + final WorkspaceImpl workspace = createWorkspace(createConfigDto()); + when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); + final int commandsSizeBefore = workspace.getConfig().getCommands().size(); + final CommandImpl firstCommand = workspace.getConfig().getCommands().iterator().next(); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .when() + .delete( + SECURE_PATH + + "/workspace/" + + workspace.getId() + + "/command/" + + firstCommand.getName()); + + assertEquals(response.getStatusCode(), 204); + assertEquals(workspace.getConfig().getCommands().size(), commandsSizeBefore - 1); + verify(wsManager).updateWorkspace(any(), any()); + } + + @Test + public void shouldAddEnvironment() throws Exception { + final WorkspaceImpl workspace = createWorkspace(createConfigDto()); + when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); + when(wsManager.updateWorkspace(any(), any())).thenReturn(workspace); + final EnvironmentDto envDto = createEnvDto(); + final int envsSizeBefore = workspace.getConfig().getEnvironments().size(); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .contentType("application/json") + .body(envDto) + .when() + .queryParam("name", "new-env") + .post(SECURE_PATH + "/workspace/" + workspace.getId() + "/environment"); + + assertEquals(response.getStatusCode(), 200); + assertEquals( + new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class), TEST_ACCOUNT) + .getConfig() + .getEnvironments() + .size(), + envsSizeBefore + 1); + verify(wsManager).updateWorkspace(any(), any()); + } + + @Test + public void shouldUpdateEnvironment() throws Exception { + final WorkspaceImpl workspace = createWorkspace(createConfigDto()); + when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); + when(wsManager.updateWorkspace(any(), any())).thenReturn(workspace); + final EnvironmentDto envDto = createEnvDto(); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .contentType("application/json") + .body(envDto) + .when() + .put( + SECURE_PATH + + "/workspace/" + + workspace.getId() + + "/environment/" + + workspace.getConfig().getDefaultEnv()); + + assertEquals(response.getStatusCode(), 200); + assertEquals(workspace.getConfig().getEnvironments().size(), 1); + verify(wsManager).updateWorkspace(any(), any()); + } + + @Test + public void shouldRespond404WhenUpdatingEnvironmentWhichDoesNotExist() throws Exception { + final WorkspaceImpl workspace = createWorkspace(createConfigDto()); + when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .contentType("application/json") + .body(createEnvDto()) + .when() + .put(SECURE_PATH + "/workspace/" + workspace.getId() + "/environment/fake"); + + assertEquals(response.getStatusCode(), 404); + assertEquals( + unwrapError(response), + "Workspace '" + workspace.getId() + "' doesn't contain environment 'fake'"); + verify(wsManager, never()).updateWorkspace(any(), any()); + } + + @Test + public void shouldDeleteEnvironment() throws Exception { + final WorkspaceImpl workspace = createWorkspace(createConfigDto()); + when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); + Map.Entry envEntry = + workspace.getConfig().getEnvironments().entrySet().iterator().next(); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .when() + .delete( + SECURE_PATH + + "/workspace/" + + workspace.getId() + + "/environment/" + + envEntry.getKey()); + + assertEquals(response.getStatusCode(), 204); + verify(wsManager).updateWorkspace(any(), any()); + } + + @Test + public void shouldRelativizeLinksOnAddEnvironment() throws Exception { + final WorkspaceImpl workspace = createWorkspace(createConfigDto()); + final String initialLocation = "http://localhost:8080/api/recipe/idrecipe123456789/script"; + when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); + when(wsManager.updateWorkspace(any(), any())).thenReturn(workspace); + final EnvironmentDto envDto = createEnvDto(); + envDto.getRecipe().withLocation(initialLocation).withType("dockerfile"); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .contentType("application/json") + .body(envDto) + .when() + .queryParam("name", "new-env") + .post(SECURE_PATH + "/workspace/" + workspace.getId() + "/environment"); + + assertEquals(response.getStatusCode(), 200); + String savedLocation = + unwrapDto(response, WorkspaceDto.class) + .getConfig() + .getEnvironments() + .get("new-env") + .getRecipe() + .getLocation(); + + assertEquals(savedLocation, initialLocation.substring(API_ENDPOINT.length())); + } + + @Test + public void shouldAddProject() throws Exception { + final WorkspaceImpl workspace = createWorkspace(createConfigDto()); + when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); + when(wsManager.updateWorkspace(any(), any())).thenReturn(workspace); + final ProjectConfigDto projectDto = createProjectDto(); + final int projectsSizeBefore = workspace.getConfig().getProjects().size(); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .contentType("application/json") + .body(projectDto) + .when() + .post(SECURE_PATH + "/workspace/" + workspace.getId() + "/project"); + + assertEquals(response.getStatusCode(), 200); + assertEquals( + new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class), TEST_ACCOUNT) + .getConfig() + .getProjects() + .size(), + projectsSizeBefore + 1); + verify(wsManager).updateWorkspace(any(), any()); + } + + @Test + public void shouldUpdateProject() throws Exception { + final WorkspaceImpl workspace = createWorkspace(createConfigDto()); + when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); + when(wsManager.updateWorkspace(any(), any())).thenReturn(workspace); + final ProjectConfigDto projectDto = createProjectDto(); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .contentType("application/json") + .body(projectDto) + .when() + .put( + SECURE_PATH + + "/workspace/" + + workspace.getId() + + "/project" + + projectDto.getPath()); + + assertEquals(response.getStatusCode(), 200); + verify(wsManager).updateWorkspace(any(), any()); + } + + @Test + public void shouldRespond404WhenUpdatingProjectWhichDoesNotExist() throws Exception { + final WorkspaceImpl workspace = createWorkspace(createConfigDto()); + when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .contentType("application/json") + .body(createProjectDto()) + .when() + .put(SECURE_PATH + "/workspace/" + workspace.getId() + "/project/fake"); + + assertEquals(response.getStatusCode(), 404); + assertEquals( + unwrapError(response), + "Workspace '" + workspace.getId() + "' doesn't contain project with path '/fake'"); + verify(wsManager, never()).updateWorkspace(any(), any()); + } + + @Test + public void shouldDeleteProject() throws Exception { + final WorkspaceImpl workspace = createWorkspace(createConfigDto()); + when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); + final ProjectConfig firstProject = workspace.getConfig().getProjects().iterator().next(); + + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .when() + .delete( + SECURE_PATH + + "/workspace/" + + workspace.getId() + + "/project" + + firstProject.getPath()); + + assertEquals(response.getStatusCode(), 204); + verify(wsManager).updateWorkspace(any(), any()); + } + + @Test + public void shouldBeAbleToGetSettings() throws Exception { + final Response response = + given() + .auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .when() + .get(SECURE_PATH + "/workspace/settings"); + + assertEquals(response.getStatusCode(), 200); + final Map settings = + new Gson().fromJson(response.print(), new TypeToken>() {}.getType()); + assertEquals(settings, emptyMap()); + } + + private static String unwrapError(Response response) { + return unwrapDto(response, ServiceError.class).getMessage(); + } + + private static T unwrapDto(Response response, Class dtoClass) { + return DtoFactory.getInstance().createDtoFromJson(response.body().print(), dtoClass); + } + + private static List unwrapDtoList(Response response, Class dtoClass) { + return DtoFactory.getInstance().createListDtoFromJson(response.body().print(), dtoClass); + } + + private static WorkspaceImpl createWorkspace(WorkspaceConfig configDto, WorkspaceStatus status) { + return WorkspaceImpl.builder() + .setConfig(configDto) + .generateId() + .setAccount(TEST_ACCOUNT) + .setStatus(status) + .build(); + } + + private static WorkspaceImpl createWorkspace(WorkspaceConfig configDto) { + return createWorkspace(configDto, WorkspaceStatus.STOPPED); + } + + private static CommandDto createCommandDto() { + return DtoConverter.asDto(new CommandImpl("MCI", "mvn clean install", "maven")); + } + + private static ProjectConfigDto createProjectDto() { + return newDto(ProjectConfigDto.class) + .withName("project-name") + .withPath("/project/path") + .withDescription("Test project") + .withMixins(new ArrayList<>(singleton("maven"))) + .withSource(newDto(SourceStorageDto.class).withLocation("location").withType("type")) + .withAttributes(new HashMap<>()); + } + + private static EnvironmentDto createEnvDto() { + MachineConfigImpl devMachine = + new MachineConfigImpl( + singletonList("org.eclipse.che.ws-agent"), + null, + singletonMap("memoryLimitBytes", "10000")); + + return DtoConverter.asDto( + new EnvironmentImpl( + new RecipeImpl("type", "content-type", "content", null), + singletonMap("dev-machine", devMachine), + emptyList())); + } + + private static WorkspaceConfigDto createConfigDto() { + final WorkspaceConfigImpl config = + WorkspaceConfigImpl.builder() + .setName("dev-workspace") + .setDefaultEnv("dev-env") + .setEnvironments(singletonMap("dev-env", new EnvironmentImpl(createEnvDto()))) + .setCommands(singletonList(createCommandDto())) + .setProjects(singletonList(createProjectDto())) + .build(); + return DtoConverter.asDto(config); + } + + @Filter + public static class EnvironmentFilter implements RequestFilter { + + public void doFilter(GenericContainerRequest request) { + EnvironmentContext.getCurrent() + .setSubject(new SubjectImpl(NAMESPACE, USER_ID, "token", false)); + } + } } diff --git a/wsmaster/che-core-api-workspace/src/test/java/org/eclipse/che/api/workspace/server/WorkspaceValidatorTest.java b/wsmaster/che-core-api-workspace/src/test/java/org/eclipse/che/api/workspace/server/WorkspaceValidatorTest.java index 3b741ab9437..9de356e897a 100644 --- a/wsmaster/che-core-api-workspace/src/test/java/org/eclipse/che/api/workspace/server/WorkspaceValidatorTest.java +++ b/wsmaster/che-core-api-workspace/src/test/java/org/eclipse/che/api/workspace/server/WorkspaceValidatorTest.java @@ -10,224 +10,245 @@ */ package org.eclipse.che.api.workspace.server; +import static java.util.Collections.singletonList; +import static java.util.Collections.singletonMap; +import static org.eclipse.che.dto.server.DtoFactory.newDto; + +import com.google.common.collect.ImmutableMap; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.eclipse.che.api.core.ValidationException; +import org.eclipse.che.api.workspace.shared.dto.CommandDto; +import org.eclipse.che.api.workspace.shared.dto.EnvironmentDto; +import org.eclipse.che.api.workspace.shared.dto.MachineConfigDto; +import org.eclipse.che.api.workspace.shared.dto.RecipeDto; +import org.eclipse.che.api.workspace.shared.dto.ServerConfigDto; +import org.eclipse.che.api.workspace.shared.dto.WorkspaceConfigDto; +import org.mockito.InjectMocks; +import org.mockito.Mock; import org.mockito.testng.MockitoTestNGListener; +import org.testng.annotations.DataProvider; import org.testng.annotations.Listeners; +import org.testng.annotations.Test; /** - * Tests for {@link WorkspaceValidator} and {@link WorkspaceValidator} + * Tests for {@link WorkspaceValidator}. * * @author Alexander Reshetnyak */ @Listeners(MockitoTestNGListener.class) public class WorkspaceValidatorTest { - // FIXME: spi - // - // @Mock - // CheEnvironmentValidator environmentValidator; - // @InjectMocks - // WorkspaceValidator wsValidator; - // - // @Test - // public void shouldValidateCorrectWorkspace() throws Exception { - // final WorkspaceConfigDto config = createConfig(); - // - // - // wsValidator.validateConfig(config); - // } - // - // @Test(expectedExceptions = BadRequestException.class, - // expectedExceptionsMessageRegExp = "Workspace name required") - // public void shouldFailValidationIfNameIsNull() throws Exception { - // final WorkspaceConfigDto config = createConfig(); - // config.withName(null); - // - // - // wsValidator.validateConfig(config); - // } - // - // @Test(dataProvider = "invalidNameProvider", - // expectedExceptions = BadRequestException.class, - // expectedExceptionsMessageRegExp = "Incorrect workspace name, it must be between 3 and 20 characters and may contain digits, " + - // "latin letters, underscores, dots, dashes and should start and end only with digits, " + - // "latin letters or underscores") - // public void shouldFailValidationIfNameIsInvalid(String name) throws Exception { - // final WorkspaceConfigDto config = createConfig(); - // config.withName(name); - // - // - // wsValidator.validateConfig(config); - // } - // - // @DataProvider(name = "invalidNameProvider") - // public static Object[][] invalidNameProvider() { - // return new Object[][] { - // {".name"}, - // {"name."}, - // {"-name"}, - // {"name-"}, - // {"long-name12345678901234567890"}, - // {"_name"}, - // {"name_"} - // }; - // } - // - // @Test(dataProvider = "validNameProvider") - // public void shouldValidateCorrectWorkspaceName(String name) throws Exception { - // final WorkspaceConfigDto config = createConfig(); - // config.withName(name); - // - // - // wsValidator.validateConfig(config); - // } - // - // @DataProvider(name = "validNameProvider") - // public static Object[][] validNameProvider() { - // return new Object[][] { - // {"name"}, - // {"quiteLongName1234567"}, - // {"name-with-dashes"}, - // {"name.with.dots"}, - // {"name0with1digits"}, - // {"mixed-symbols.name12"}, - // {"123456"}, - // {"name_name"}, - // {"123-456.78"} - // }; - // } - // - // @Test(expectedExceptions = BadRequestException.class, - // expectedExceptionsMessageRegExp = "Attribute name 'null' is not valid") - // public void shouldFailValidationIfAttributeNameIsNull() throws Exception { - // final AccountImpl account = new AccountImpl("accountId", "namespace", "test"); - // final WorkspaceImpl workspace = new WorkspaceImpl("id", account, createConfig()); - // workspace.getAttributes().put(null, "value1"); - // - // - // wsValidator.validateWorkspace(workspace); - // } - // - // @Test(expectedExceptions = BadRequestException.class, - // expectedExceptionsMessageRegExp = "Attribute name '' is not valid") - // public void shouldFailValidationIfAttributeNameIsEmpty() throws Exception { - // final AccountImpl account = new AccountImpl("accountId", "namespace", "test"); - // final WorkspaceImpl workspace = new WorkspaceImpl("id", account, createConfig()); - // workspace.getAttributes().put("", "value1"); - // - // wsValidator.validateWorkspace(workspace); - // } - // - // @Test(expectedExceptions = BadRequestException.class, - // expectedExceptionsMessageRegExp = "Attribute name '.*' is not valid") - // public void shouldFailValidationIfAttributeNameStartsWithWordCodenvy() throws Exception { - // final AccountImpl account = new AccountImpl("accountId", "namespace", "test"); - // final WorkspaceImpl workspace = new WorkspaceImpl("id", account, createConfig()); - // workspace.getAttributes().put("codenvy_key", "value1"); - // - // wsValidator.validateWorkspace(workspace); - // } - // - // @Test(expectedExceptions = BadRequestException.class, - // expectedExceptionsMessageRegExp = "Workspace default environment name required") - // public void shouldFailValidationIfDefaultEnvNameIsNull() throws Exception { - // final WorkspaceConfigDto config = createConfig(); - // config.setDefaultEnv(null); - // - // - // wsValidator.validateConfig(config); - // } - // - // @Test(expectedExceptions = BadRequestException.class, - // expectedExceptionsMessageRegExp = "Workspace default environment name required") - // public void shouldFailValidationIfDefaultEnvNameIsEmpty() throws Exception { - // final WorkspaceConfigDto config = createConfig(); - // config.setDefaultEnv(""); - // - // - // wsValidator.validateConfig(config); - // } - // - // @Test(expectedExceptions = BadRequestException.class, - // expectedExceptionsMessageRegExp = "Workspace default environment configuration required") - // public void shouldFailValidationIfEnvWithDefaultEnvNameIsNull() throws Exception { - // final WorkspaceConfigDto config = createConfig(); - // config.setEnvironments(null); - // - // - // wsValidator.validateConfig(config); - // } - // - // @Test(expectedExceptions = BadRequestException.class, - // expectedExceptionsMessageRegExp = "Workspace ws-name contains command with null or empty name") - // public void shouldFailValidationIfCommandNameIsNull() throws Exception { - // final WorkspaceConfigDto config = createConfig(); - // config.getCommands() - // .get(0) - // .withName(null); - // - // - // wsValidator.validateConfig(config); - // } - // - // @Test(expectedExceptions = BadRequestException.class, - // expectedExceptionsMessageRegExp = "Workspace ws-name contains command with null or empty name") - // public void shouldFailValidationIfCommandNameIsEmpty() throws Exception { - // final WorkspaceConfigDto config = createConfig(); - // config.getCommands() - // .get(0) - // .withName(null); - // - // - // wsValidator.validateConfig(config); - // } - // - // @Test(expectedExceptions = BadRequestException.class, - // expectedExceptionsMessageRegExp = "Command line required for command '.*'") - // public void shouldFailValidationIfCommandLineIsNull() throws Exception { - // final WorkspaceConfigDto config = createConfig(); - // config.getCommands() - // .get(0) - // .withCommandLine(null); - // - // - // wsValidator.validateConfig(config); - // } - // - // @Test(expectedExceptions = BadRequestException.class, - // expectedExceptionsMessageRegExp = "Command line required for command '.*'") - // public void shouldFailValidationIfCommandLineIsEmpty() throws Exception { - // final WorkspaceConfigDto config = createConfig(); - // config.getCommands() - // .get(0) - // .withCommandLine(""); - // - // - // wsValidator.validateConfig(config); - // } - // - // private static WorkspaceConfigDto createConfig() { - // final WorkspaceConfigDto workspaceConfigDto = newDto(WorkspaceConfigDto.class).withName("ws-name") - // .withDefaultEnv("dev-env"); - // - // MachineConfigDto extendedMachine = - // newDto(MachineConfigDto.class).withInstallers(singletonList("org.eclipse.che.ws-agent")) - // .withServers(singletonMap("ref1", - // newDto(ServerConfigDto.class).withPort("8080/tcp") - // .withProtocol("https"))) - // .withAttributes(singletonMap("memoryLimitBytes", "1000000")); - // EnvironmentDto env = newDto(EnvironmentDto.class).withMachines(singletonMap("devmachine1", extendedMachine)) - // .withRecipe(newDto(RecipeDto.class).withType("type") - // .withContent("content") - // .withContentType("content type")); - // workspaceConfigDto.setEnvironments(singletonMap("dev-env", env)); - // - // List commandDtos = new ArrayList<>(); - // commandDtos.add(newDto(CommandDto.class).withName("command_name") - // .withType("maven") - // .withCommandLine("mvn clean install") - // .withAttributes(new HashMap<>(singletonMap("cmd-attribute-name", - // "cmd-attribute-value")))); - // workspaceConfigDto.setCommands(commandDtos); - // - // return workspaceConfigDto; - // } + @Mock private WorkspaceRuntimes workspaceRuntimes; + + @InjectMocks private WorkspaceValidator wsValidator; + + @Test + public void shouldValidateCorrectWorkspace() throws Exception { + final WorkspaceConfigDto config = createConfig(); + + wsValidator.validateConfig(config); + } + + @Test( + expectedExceptions = ValidationException.class, + expectedExceptionsMessageRegExp = "Workspace name required" + ) + public void shouldFailValidationIfNameIsNull() throws Exception { + final WorkspaceConfigDto config = createConfig(); + config.withName(null); + + wsValidator.validateConfig(config); + } + + @Test( + dataProvider = "invalidNameProvider", + expectedExceptions = ValidationException.class, + expectedExceptionsMessageRegExp = + "Incorrect workspace name, it must be between 3 and 20 " + + "characters and may contain digits, latin letters, underscores, dots, dashes and must " + + "start and end only with digits, latin letters or underscores" + ) + public void shouldFailValidationIfNameIsInvalid(String name) throws Exception { + final WorkspaceConfigDto config = createConfig(); + config.withName(name); + + wsValidator.validateConfig(config); + } + + @DataProvider(name = "invalidNameProvider") + public static Object[][] invalidNameProvider() { + return new Object[][] { + {".name"}, + {"name."}, + {"-name"}, + {"name-"}, + {"long-name12345678901234567890"}, + {"_name"}, + {"name_"} + }; + } + + @Test(dataProvider = "validNameProvider") + public void shouldValidateCorrectWorkspaceName(String name) throws Exception { + final WorkspaceConfigDto config = createConfig(); + config.withName(name); + + wsValidator.validateConfig(config); + } + + @DataProvider(name = "validNameProvider") + public static Object[][] validNameProvider() { + return new Object[][] { + {"name"}, + {"quiteLongName1234567"}, + {"name-with-dashes"}, + {"name.with.dots"}, + {"name0with1digits"}, + {"mixed-symbols.name12"}, + {"123456"}, + {"name_name"}, + {"123-456.78"} + }; + } + + @Test( + expectedExceptions = ValidationException.class, + expectedExceptionsMessageRegExp = "Attribute name 'null' is not valid" + ) + public void shouldFailValidationIfAttributeNameIsNull() throws Exception { + Map attributes = new HashMap<>(); + attributes.put(null, "value1"); + + wsValidator.validateAttributes(attributes); + } + + @Test( + expectedExceptions = ValidationException.class, + expectedExceptionsMessageRegExp = "Attribute name '' is not valid" + ) + public void shouldFailValidationIfAttributeNameIsEmpty() throws Exception { + wsValidator.validateAttributes(ImmutableMap.of("", "value1")); + } + + @Test( + expectedExceptions = ValidationException.class, + expectedExceptionsMessageRegExp = "Attribute name 'codenvy_key' is not valid" + ) + public void shouldFailValidationIfAttributeNameStartsWithWordCodenvy() throws Exception { + wsValidator.validateAttributes(ImmutableMap.of("codenvy_key", "value1")); + } + + @Test( + expectedExceptions = ValidationException.class, + expectedExceptionsMessageRegExp = "Workspace default environment name required" + ) + public void shouldFailValidationIfDefaultEnvNameIsNull() throws Exception { + final WorkspaceConfigDto config = createConfig(); + config.setDefaultEnv(null); + + wsValidator.validateConfig(config); + } + + @Test( + expectedExceptions = ValidationException.class, + expectedExceptionsMessageRegExp = "Workspace default environment name required" + ) + public void shouldFailValidationIfDefaultEnvNameIsEmpty() throws Exception { + final WorkspaceConfigDto config = createConfig(); + config.setDefaultEnv(""); + + wsValidator.validateConfig(config); + } + + @Test( + expectedExceptions = ValidationException.class, + expectedExceptionsMessageRegExp = "Workspace default environment configuration required" + ) + public void shouldFailValidationIfEnvWithDefaultEnvNameIsNull() throws Exception { + final WorkspaceConfigDto config = createConfig(); + config.setEnvironments(null); + + wsValidator.validateConfig(config); + } + + @Test( + expectedExceptions = ValidationException.class, + expectedExceptionsMessageRegExp = "Workspace ws-name contains command with null or empty name" + ) + public void shouldFailValidationIfCommandNameIsNull() throws Exception { + final WorkspaceConfigDto config = createConfig(); + config.getCommands().get(0).withName(null); + + wsValidator.validateConfig(config); + } + + @Test( + expectedExceptions = ValidationException.class, + expectedExceptionsMessageRegExp = "Workspace ws-name contains command with null or empty name" + ) + public void shouldFailValidationIfCommandNameIsEmpty() throws Exception { + final WorkspaceConfigDto config = createConfig(); + config.getCommands().get(0).withName(null); + + wsValidator.validateConfig(config); + } + + @Test( + expectedExceptions = ValidationException.class, + expectedExceptionsMessageRegExp = "Command line required for command '.*'" + ) + public void shouldFailValidationIfCommandLineIsNull() throws Exception { + final WorkspaceConfigDto config = createConfig(); + config.getCommands().get(0).withCommandLine(null); + + wsValidator.validateConfig(config); + } + + @Test( + expectedExceptions = ValidationException.class, + expectedExceptionsMessageRegExp = "Command line required for command '.*'" + ) + public void shouldFailValidationIfCommandLineIsEmpty() throws Exception { + final WorkspaceConfigDto config = createConfig(); + config.getCommands().get(0).withCommandLine(""); + + wsValidator.validateConfig(config); + } + + private static WorkspaceConfigDto createConfig() { + final WorkspaceConfigDto workspaceConfigDto = + newDto(WorkspaceConfigDto.class).withName("ws-name").withDefaultEnv("dev-env"); + + MachineConfigDto extendedMachine = + newDto(MachineConfigDto.class) + .withInstallers(singletonList("org.eclipse.che.ws-agent")) + .withServers( + singletonMap( + "ref1", + newDto(ServerConfigDto.class).withPort("8080/tcp").withProtocol("https"))) + .withAttributes(singletonMap("memoryLimitBytes", "1000000")); + EnvironmentDto env = + newDto(EnvironmentDto.class) + .withMachines(singletonMap("devmachine1", extendedMachine)) + .withRecipe( + newDto(RecipeDto.class) + .withType("type") + .withContent("content") + .withContentType("content type")); + workspaceConfigDto.setEnvironments(singletonMap("dev-env", env)); + + List commandDtos = new ArrayList<>(); + commandDtos.add( + newDto(CommandDto.class) + .withName("command_name") + .withType("maven") + .withCommandLine("mvn clean install") + .withAttributes( + new HashMap<>(singletonMap("cmd-attribute-name", "cmd-attribute-value")))); + workspaceConfigDto.setCommands(commandDtos); + + return workspaceConfigDto; + } }