Remove CF client and boot dash plugins and related tests

This commit is contained in:
aboyko
2023-03-07 18:46:46 -05:00
parent 9fe72953ca
commit 9185656e02
273 changed files with 27 additions and 33927 deletions

View File

@@ -29,7 +29,6 @@ Require-Bundle: org.junit,
org.eclipse.lsp4e,
org.eclipse.lsp4j,
org.springframework.ide.eclipse.boot.dash;bundle-version="3.9.12",
org.springframework.ide.eclipse.boot.dash.cf;bundle-version="3.9.12",
org.springframework.ide.eclipse.beans.ui.live,
org.eclipse.jface.text,
org.eclipse.ui.editors,
@@ -38,8 +37,6 @@ Require-Bundle: org.junit,
org.eclipse.ui.ide,
org.springsource.ide.eclipse.commons.core,
org.yaml.snakeyaml,
org.springsource.ide.eclipse.commons.cloudfoundry.client.v2,
org.springframework.tooling.cloudfoundry.manifest.ls,
org.springframework.tooling.ls.eclipse.commons,
org.springframework.ide.eclipse.boot.dash.docker;bundle-version="3.9.13",
org.springframework.ide.eclipse.buildship30,

View File

@@ -62,16 +62,6 @@
<id>org.eclipse.m2e.feature</id>
<versionRange>0.0.0</versionRange>
</requirement>
<requirement>
<type>eclipse-feature</type>
<id>org.springframework.tooling.cloudfoundry.manifest.ls.feature</id>
<versionRange>0.0.0</versionRange>
</requirement>
<requirement>
<type>eclipse-plugin</type>
<id>org.springframework.ide.eclipse.boot.dash.cf</id>
<versionRange>0.0.0</versionRange>
</requirement>
</extraRequirements>
</dependency-resolution>
</configuration>

View File

@@ -13,13 +13,7 @@ package org.springframework.ide.eclipse.boot.dash.test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import org.springframework.ide.eclipse.boot.dash.docker.ui.SelectDockerDaemonDialog;
import org.springframework.ide.eclipse.boot.dash.test.actuator.ActuatorDataTest;
import org.springframework.ide.eclipse.boot.dash.test.yaml.AppNameReconcilerTest;
import org.springframework.ide.eclipse.boot.dash.test.yaml.CFRouteTests;
import org.springframework.ide.eclipse.boot.dash.test.yaml.DeploymentProperties2YamlTest;
import org.springframework.ide.eclipse.boot.dash.test.yaml.ManifestCompareMergeTests;
import org.springframework.ide.eclipse.boot.dash.test.yaml.Yaml2DeploymentPropertiesTest;
@RunWith(Suite.class)
@SuiteClasses({
@@ -28,42 +22,27 @@ import org.springframework.ide.eclipse.boot.dash.test.yaml.Yaml2DeploymentProper
// Raised up temporarily to be run first.
BootDashDockerTests.class, //50 seconds
SelectDockerDaemonDialogTest.class,
// BootDashDockerTests.class, //50 seconds
// SelectDockerDaemonDialogTest.class,
//New: (move down the chain later based on runtime)
JmxSupportTest.class,
PropertyFileStoreTest.class,
// Manifest YAML/Deployment Properties tests (less than 2 seconds per suite)
DeploymentProperties2YamlTest.class,
Yaml2DeploymentPropertiesTest.class,
AppNameReconcilerTest.class,
RouteBuilderTest.class,
CFRouteTests.class,
//Really short (less than 2 seconds per suite):
JLRMethodParserTest.class,
OrderBasedComparatorTest.class,
ManifestCompareMergeTests.class,
AbstractLaunchConfigurationsDashElementTest.class,
BootDashElementTagsTests.class,
ActuatorDataTest.class,
ToggleFiltersModelTest.class,
//Medium length (less than 30 seconds):
JarNameGeneratorTest.class,
BootDashViewModelTest.class,
BootJarPackagingTest.class,
BeanResourceDefinitionParsingTests.class,
//Long tests (more than 30 seconds):
CloudFoundryBootDashModelMockingTest.class,
DeploymentPropertiesDialogModelTests.class,
BootDashActionTests.class,
BootDashModelTest.class,
CloudFoundryClientTest.class,
CloudFoundryBootDashModelIntegrationTest.class,
})
public class AllBootDashTests {

View File

@@ -10,9 +10,8 @@
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test;
import org.springframework.ide.eclipse.boot.dash.cf.ui.CfUserInteractions;
import org.springframework.ide.eclipse.boot.dash.model.UserInteractions;
import org.springframework.ide.eclipse.boot.dash.docker.ui.DockerUserInteractions;
public interface AllUserInteractions extends UserInteractions, CfUserInteractions, DockerUserInteractions {
public interface AllUserInteractions extends UserInteractions, DockerUserInteractions {
}

View File

@@ -16,7 +16,6 @@ import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
@@ -24,7 +23,6 @@ import java.util.EnumSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -41,10 +39,6 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.ide.eclipse.boot.dash.cf.model.CloudAppDashElement;
import org.springframework.ide.eclipse.boot.dash.cf.model.CloudFoundryBootDashModel;
import org.springframework.ide.eclipse.boot.dash.cf.runtarget.CloudFoundryRunTarget;
import org.springframework.ide.eclipse.boot.dash.cf.runtarget.CloudFoundryRunTargetType;
import org.springframework.ide.eclipse.boot.dash.di.SimpleDIContext;
import org.springframework.ide.eclipse.boot.dash.liveprocess.LiveDataConnectionManagementActions;
import org.springframework.ide.eclipse.boot.dash.model.AbstractLaunchConfigurationsDashElement;
@@ -71,7 +65,6 @@ import org.springframework.ide.eclipse.boot.test.AutobuildingEnablement;
import org.springframework.ide.eclipse.boot.test.BootProjectTestHarness;
import org.springframework.ide.eclipse.boot.test.BootProjectTestHarness.WizardConfigurer;
import org.springframework.ide.eclipse.boot.test.util.TestBracketter;
import org.springsource.ide.eclipse.commons.core.pstore.InMemoryPropertyStore;
import org.springsource.ide.eclipse.commons.frameworks.test.util.ACondition;
import org.springsource.ide.eclipse.commons.livexp.core.LiveExpression;
import org.springsource.ide.eclipse.commons.livexp.core.LiveVariable;
@@ -387,16 +380,6 @@ public class BootDashActionTests {
}
}
{
CloudAppDashElement cfElement = mockCfElement(appGuid, "demo-app");
selection.setElements(cfElement);
List<IAction> actions = liveActionsMenu.getActions();
Set<String> actualLabels = actions.stream().map(IAction::getText).collect(Collectors.toSet());
assertEquals(ImmutableSet.of("Connect remote process 1 (lbl)"), actualLabels);
for (IAction ac : actions) {
assertTrue(ac.isEnabled());
}
}
}
private IAction assertActionWithLabel(List<IAction> actions, String expectedLabel) {
@@ -1008,20 +991,4 @@ public class BootDashActionTests {
return element;
}
private CloudAppDashElement mockCfElement(String appGuid, String appName) {
CloudFoundryRunTarget cfTarget = mock(CloudFoundryRunTarget.class);
CloudFoundryRunTargetType cfType = mock(CloudFoundryRunTargetType.class);
when(cfTarget.getType()).thenReturn(cfType);
CloudFoundryBootDashModel model = mock(CloudFoundryBootDashModel.class);
when(model.getRunTarget()).thenReturn(cfTarget);
CloudAppDashElement element = spy(new CloudAppDashElement(model, appName, new InMemoryPropertyStore()));
when(element.getAppGuid()).thenReturn(UUID.fromString(appGuid));
when(element.getName()).thenReturn(appName);
when(element.supportedGoalStates()).thenReturn(CloudFoundryRunTarget.RUN_GOAL_STATES);
when(element.getTarget()).thenReturn(cfTarget);
return element;
}
}

View File

@@ -82,7 +82,6 @@ import org.springframework.ide.eclipse.boot.core.cli.BootCliCommand;
import org.springframework.ide.eclipse.boot.core.cli.BootInstallManager;
import org.springframework.ide.eclipse.boot.core.cli.install.CloudCliInstall;
import org.springframework.ide.eclipse.boot.core.cli.install.IBootInstall;
import org.springframework.ide.eclipse.boot.dash.cf.model.CloudServiceInstanceDashElement;
import org.springframework.ide.eclipse.boot.dash.model.BootDashElement;
import org.springframework.ide.eclipse.boot.dash.model.BootDashElementsFilterBoxModel;
import org.springframework.ide.eclipse.boot.dash.model.BootDashModel;
@@ -1534,8 +1533,7 @@ public class BootDashModelTest {
}
private boolean isService(BootDashElement e) {
return e instanceof LocalCloudServiceDashElement
|| e instanceof CloudServiceInstanceDashElement;
return e instanceof LocalCloudServiceDashElement;
}
public void waitNonServiceElements(final String... expectedElementNames) throws Exception {

View File

@@ -16,9 +16,9 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.contains;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
@@ -38,28 +38,19 @@ import org.eclipse.debug.core.ILaunchConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFCredentials;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFCredentials.CFCredentialType;
import org.springframework.ide.eclipse.boot.dash.cf.dialogs.StoreCredentialsMode;
import org.springframework.ide.eclipse.boot.dash.cf.runtarget.CloudFoundryTargetProperties;
import org.springframework.ide.eclipse.boot.dash.di.SimpleDIContext;
import org.springframework.ide.eclipse.boot.dash.api.RunTargetType;
import org.springframework.ide.eclipse.boot.dash.model.BootDashElement;
import org.springframework.ide.eclipse.boot.dash.model.BootDashModel;
import org.springframework.ide.eclipse.boot.dash.model.BootDashModel.ElementStateListener;
import org.springframework.ide.eclipse.boot.dash.model.BootDashModelContext;
import org.springframework.ide.eclipse.boot.dash.model.BootDashViewModel;
import org.springframework.ide.eclipse.boot.dash.model.BootProjectDashElement;
import org.springframework.ide.eclipse.boot.dash.model.RunTarget;
import org.springframework.ide.eclipse.boot.dash.model.RunTargets;
import org.springframework.ide.eclipse.boot.dash.model.SecuredCredentialsStore;
import org.springframework.ide.eclipse.boot.dash.model.ToggleFiltersModel.FilterChoice;
import org.springframework.ide.eclipse.boot.dash.model.UserInteractions;
import org.springframework.ide.eclipse.boot.dash.api.RunTargetType;
import org.springframework.ide.eclipse.boot.dash.model.runtargettypes.RunTargetTypes;
import org.springframework.ide.eclipse.boot.dash.model.runtargettypes.TargetProperties;
import org.springframework.ide.eclipse.boot.dash.test.mocks.MockBootDashModel;
import org.springframework.ide.eclipse.boot.dash.test.mocks.MockRunTarget;
import org.springframework.ide.eclipse.boot.dash.test.mocks.MockRunTargetType;
import org.springframework.ide.eclipse.boot.launch.BootLaunchConfigurationDelegate;
import org.springframework.ide.eclipse.boot.test.BootProjectTestHarness;
import org.springsource.ide.eclipse.commons.livexp.core.LiveExpression;
@@ -529,38 +520,6 @@ public class BootDashViewModelTest {
}
@Test
public void testRestoreSingleRunTarget() throws Exception {
context.injections.def(MockRunTargetType.class, injections -> {
MockRunTargetType targetType = new MockRunTargetType(injections, "MOCK");
return targetType;
});
String targetId = "foo";
harness = new BootDashViewModelHarness(context);
MockRunTargetType targetType = context.injections.getBean(MockRunTargetType.class);
CloudFoundryTargetProperties props = new CloudFoundryTargetProperties(null, targetType, context.injections);
props.put(TargetProperties.RUN_TARGET_ID, targetId);
props.put("describe", "This is foo");
RunTarget<CloudFoundryTargetProperties> savedTarget = targetType.createRunTarget(props);
harness.model.getRunTargets().add(savedTarget);
BootDashModelContext oldContext = harness.context;
harness.reload();
MockRunTarget restoredTarget = (MockRunTarget)harness.getRunTarget(targetType);
//Not a stric requirement, but it would be a little strange of the restored
// target was the exact same object as the saved target (the test may be broken
// or some state in the model is not cleaned up when it is disposed)
assertTrue(restoredTarget != savedTarget);
assertEquals(savedTarget, restoredTarget);
assertEquals("This is foo", restoredTarget.get("describe"));
}
@Test
public void testModelComparator() throws Exception {
//View model is expected to provide a comparator that is based on
@@ -568,8 +527,6 @@ public class BootDashViewModelTest {
//models based on type first then runtarget id second.
context.withTargetTypes(RunTargetTypes.LOCAL);
context.injections.def(RunTargetType.class, injections -> new MockRunTargetType(context.injections, "foo-type"));
context.injections.def(RunTargetType.class, injections -> new MockRunTargetType(context.injections, "bar-type"));
harness = new BootDashViewModelHarness(context);
Comparator<BootDashModel> comparator = harness.model.getModelComparator();
@@ -622,127 +579,4 @@ public class BootDashViewModelTest {
return model;
}
@Test
public void testUpdatePropertiesInStore() throws Exception {
context.injections.def(MockRunTargetType.class, injections -> {
MockRunTargetType targetType = new MockRunTargetType(injections, "mock-type");
targetType.setRequiresCredentials(true);
return targetType;
});
harness = new BootDashViewModelHarness(context);
MockRunTargetType targetType = context.injections.getBean(MockRunTargetType.class);
CloudFoundryTargetProperties properties = new CloudFoundryTargetProperties(null, targetType, context.injections);
properties.setCredentials(CFCredentials.fromPassword("secret"));
MockRunTarget target = (MockRunTarget) targetType.createRunTarget(properties);
harness.model.getRunTargets().add(target);
harness.model.updateTargetPropertiesInStore();
assertEquals("secret", ((CloudFoundryTargetProperties)target.getTargetProperties()).getCredentials().getSecret());
harness.reload();
MockRunTarget restoredTarget = (MockRunTarget) harness.getRunTarget(targetType);
assertTrue(restoredTarget != target); //Not a strict requirement, but it is more or less
// expected the restored target is a brand new object
//TODO: Strange test. Shouldn't there be something to check here?
}
@Test
public void testRememberPassword() throws Exception {
context.injections.def(MockRunTargetType.class, injections -> {
MockRunTargetType targetType = new MockRunTargetType(injections, "mock-type");
targetType.setRequiresCredentials(true);
return targetType;
});
harness = new BootDashViewModelHarness(context);
MockRunTargetType targetType = context.injections.getBean(MockRunTargetType.class);
CloudFoundryTargetProperties properties = new CloudFoundryTargetProperties(null, targetType, context.injections);
properties.put(TargetProperties.RUN_TARGET_ID, "target-id");
properties.setStoreCredentials(StoreCredentialsMode.STORE_PASSWORD);
properties.setCredentials(CFCredentials.fromPassword("secret"));
MockRunTarget target = (MockRunTarget) targetType.createRunTarget(properties);
harness.model.getRunTargets().add(target);
harness.model.updateTargetPropertiesInStore();
SecuredCredentialsStore secureStore = harness.context.getSecuredCredentialsStore();
//This test needs to have knowledge what keys the passwords are store under.
// That seems undesirable.
String key = "mock-type:target-id";
{
CloudFoundryTargetProperties targetProperties = (CloudFoundryTargetProperties) target.getTargetProperties();
assertEquals(StoreCredentialsMode.STORE_PASSWORD, targetProperties.getStoreCredentials());
assertEquals(CFCredentialType.PASSWORD, targetProperties.getCredentials().getType());
assertEquals("secret", targetProperties.getCredentials().getSecret());
assertEquals("secret", secureStore.getCredentials(key));
}
/////////////////////////////////////////
// check that when runtargets are restored from the store the password prop is properly
// restored
harness.reload();
MockRunTarget restoredTarget = (MockRunTarget) harness.getRunTarget(targetType);
assertTrue(restoredTarget != target); //Not a strict requirement, but it is more or less
// expected the restored target is a brand new object
{
CloudFoundryTargetProperties restoredTargetProperties = (CloudFoundryTargetProperties) restoredTarget.getTargetProperties();
assertEquals(StoreCredentialsMode.STORE_PASSWORD, restoredTargetProperties.getStoreCredentials());
assertEquals("secret", restoredTargetProperties.getCredentials().getSecret());
}
}
@Test
public void testDontRememberPassword() throws Exception {
context.injections.def(MockRunTargetType.class, injections -> {
MockRunTargetType targetType = new MockRunTargetType(injections, "mock-type");
targetType.setRequiresCredentials(true);
return targetType;
});
harness = new BootDashViewModelHarness(context);
MockRunTargetType targetType = context.injections.getBean(MockRunTargetType.class);
CloudFoundryTargetProperties properties = new CloudFoundryTargetProperties(null, targetType, context.injections);
properties.setStoreCredentials(StoreCredentialsMode.STORE_NOTHING);
properties.setCredentials(CFCredentials.fromPassword("secret"));
MockRunTarget target = (MockRunTarget) targetType.createRunTarget(properties);
harness.model.getRunTargets().add(target);
harness.model.updateTargetPropertiesInStore();
SecuredCredentialsStore secureStore = harness.context.getSecuredCredentialsStore();
//This test needs to have knowledge what keys the passwords are store under.
// That seems undesirable.
String key = "mock-type:target-id";
{
CloudFoundryTargetProperties targetProperties = (CloudFoundryTargetProperties) target.getTargetProperties();
assertEquals(StoreCredentialsMode.STORE_NOTHING, targetProperties.getStoreCredentials());
assertEquals("secret", targetProperties.getCredentials().getSecret());
assertNull(secureStore.getCredentials(key));
}
/////////////////////////////////////////
// check that when runtargets are restored from the store the password is not remebered
harness.reload();
MockRunTarget restoredTarget = (MockRunTarget) harness.getRunTarget(targetType);
assertTrue(restoredTarget != target); //Not a strict requirement, but it is more or less
// expected the restored target is a brand new object
{
CloudFoundryTargetProperties restoredTargetProperties = (CloudFoundryTargetProperties) restoredTarget.getTargetProperties();
assertEquals(StoreCredentialsMode.STORE_NOTHING,restoredTargetProperties.getStoreCredentials());
assertNull(restoredTargetProperties.getCredentials());
}
}
}

View File

@@ -1,163 +0,0 @@
/*******************************************************************************
* Copyright (c) 2015 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test;
import static org.springsource.ide.eclipse.commons.tests.util.StsTestUtil.assertNoErrors;
import java.io.File;
import java.util.jar.JarFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.mockito.Mockito;
import org.springframework.ide.eclipse.boot.dash.BootDashActivator;
import org.springframework.ide.eclipse.boot.dash.cf.packaging.CloudApplicationArchiverStrategies;
import org.springframework.ide.eclipse.boot.dash.cf.packaging.CloudApplicationArchiverStrategy;
import org.springframework.ide.eclipse.boot.dash.cf.packaging.ICloudApplicationArchiver;
import org.springframework.ide.eclipse.boot.dash.model.UserInteractions;
import org.springframework.ide.eclipse.boot.test.BootProjectTestHarness;
import org.springframework.ide.eclipse.boot.test.util.JavaUtils;
import org.springframework.ide.eclipse.boot.test.util.LaunchResult;
import org.springsource.ide.eclipse.commons.tests.util.StsTestCase;
import org.springsource.ide.eclipse.commons.tests.util.StsTestUtil;
import static org.springframework.ide.eclipse.boot.test.BootProjectTestHarness.setPackage;
public class BootJarPackagingTest extends StsTestCase {
private JavaUtils java = new JavaUtils();
@Override
protected void setUp() throws Exception {
super.setUp();
StsTestUtil.deleteAllProjects();
StsTestUtil.setAutoBuilding(false);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public void testSimple() throws Exception {
UserInteractions ui = Mockito.mock(UserInteractions.class);
BootProjectTestHarness harness = getHarness();
IProject project = harness.createBootProject("simple-boot",
setPackage("demo")
);
createFile(project, "src/main/java/demo/Greeter.java",
"package demo;\n" +
"\n" +
"import org.springframework.boot.CommandLineRunner;\n" +
"import org.springframework.stereotype.Component;\n" +
"\n" +
"@Component\n" +
"public class Greeter implements CommandLineRunner {\n" +
"\n" +
" @Override\n" +
" public void run(String... arg0) throws Exception {\n" +
" System.out.println(\"Hello World!\");\n" +
" }\n" +
"\n" +
"}\n"
);
StsTestUtil.assertNoErrors(project); // Builds the project
File jarFile = packageAsJar(project, ui);
LaunchResult result = java.runJar(jarFile);
assertContains("Hello World!", result.out);
assertEquals(0, result.terminationCode);
Mockito.verifyZeroInteractions(ui);
}
public void testProjectDependency() throws Exception {
IProject depProject = createPredefinedProject("demo-lib");
StsTestUtil.assertNoErrors(depProject);
UserInteractions ui = Mockito.mock(UserInteractions.class);
BootProjectTestHarness harness = getHarness();
IProject project = harness.createBootProject("simple-boot",
setPackage("demo")
);
fileReplace(project, "pom.xml",
"</dependencies>",
" <dependency>\n" +
" <groupId>org.demo</groupId>\n" +
" <artifactId>demo-lib</artifactId>\n" +
" <version>0.0.1</version>\n" +
" </dependency>\n" +
" </dependencies>");
createFile(project, "src/main/java/demo/Greeter.java",
"package demo;\n" +
"\n" +
"import org.demo.lib.TheLib;\n" +
"import org.springframework.boot.CommandLineRunner;\n" +
"import org.springframework.stereotype.Component;\n" +
"\n" +
"@Component\n" +
"public class Greeter implements CommandLineRunner {\n" +
"\n" +
" @Override\n" +
" public void run(String... arg0) throws Exception {\n" +
" System.out.println(TheLib.createGreeting(\"Kris\"));\n" +
" }\n" +
"\n" +
"}\n"
);
assertNoErrors(project);
File jarFile = packageAsJar(project, ui);
assertEntries(jarFile,
"lib/demo-lib.jar"
);
LaunchResult result = java.runJar(jarFile);
assertContains("Hello, Kris!", result.out);
assertEquals(0, result.terminationCode);
Mockito.verifyZeroInteractions(ui);
}
/**
* Verifies that jarFile has at least a given list of entries (in any order).
*/
private void assertEntries(File file, String... expected) throws Exception {
JarFile jarFile = new JarFile(file);
try {
for (String name : expected) {
assertNotNull("Missing expected Jar Entry: "+name, jarFile.getJarEntry(name));
}
} finally {
jarFile.close();
}
}
public static File packageAsJar(IProject project, UserInteractions ui) throws Exception {
CloudApplicationArchiverStrategy strategy = CloudApplicationArchiverStrategies.packageAsJar(project, ui);
ICloudApplicationArchiver archiver = strategy.getArchiver(new NullProgressMonitor());
assertNotNull(archiver);
File jar = archiver.getApplicationArchive(new NullProgressMonitor());
assertNotNull(jar);
assertTrue(jar.isFile());
return jar;
}
private BootProjectTestHarness getHarness() {
return new BootProjectTestHarness(ResourcesPlugin.getWorkspace());
}
@Override
protected String getBundleName() {
return BootDashTestBundleConstants.BUNDLE_ID;
}
}

View File

@@ -1,92 +0,0 @@
/*******************************************************************************
* Copyright (c) 2015 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import org.eclipse.core.runtime.Assert;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFClientParams;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFCredentials;
import org.springsource.ide.eclipse.commons.frameworks.core.util.StringUtils;
/**
* @author Kris De Volder
*/
public class CfTestTargetParams {
public static CFClientParams fromEnv() {
try {
return new CFClientParams(
fromEnv("CF_TEST_API_URL"),
fromEnv("CF_TEST_USER"),
CFCredentials.fromPassword(fromEnv("CF_TEST_PASSWORD")),
false, //self signed
fromEnv("CF_TEST_ORG"),
fromEnvOrFile("CF_TEST_SPACE"),
fromEnvBoolean("CF_TEST_SKIP_SSL")
);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static String fromEnvOrFile(String name) throws IOException {
String envVal = getEnvMaybe(name);
if (envVal!=null) {
return envVal;
} else {
String fileName = fromEnv(name+"_FILE");
Path path = FileSystems.getDefault().getPath(fileName);
return Files.readAllLines(path).get(0);
}
}
private static String getEnvMaybe(String name) {
String val = System.getenv(name);
if (!StringUtils.hasText(val)) {
val = System.getenv("bamboo_"+name);
}
return val;
}
public static String fromEnv(String name) {
String value = getEnvMaybe(name);
Assert.isLegal(StringUtils.hasText(value), "The environment varable '"+name+"' must be set");
return value;
}
private static boolean fromEnvBoolean(String name) {
String value = getEnvMaybe(name);
if (value == null) {
return false;
}
return Boolean.parseBoolean(value);
}
public static CFClientParams fromEnvWithCredentials(CFCredentials credentials) {
try {
return new CFClientParams(
fromEnv("CF_TEST_API_URL"),
fromEnv("CF_TEST_USER"),
credentials,
false, //self signed
fromEnv("CF_TEST_ORG"),
fromEnvOrFile("CF_TEST_SPACE"),
fromEnvBoolean("CF_TEST_SKIP_SSL")
);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

View File

@@ -1,97 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.junit.Assert.fail;
import java.util.HashSet;
import java.util.Set;
import org.springframework.ide.eclipse.boot.dash.cf.client.v2.DefaultClientRequestsV2;
import org.springframework.ide.eclipse.boot.dash.console.IApplicationLogConsole;
import org.springframework.ide.eclipse.boot.dash.console.LogMessage;
import org.springsource.ide.eclipse.commons.core.util.StringUtil;
import org.springsource.ide.eclipse.commons.livexp.core.AbstractDisposable;
import org.springsource.ide.eclipse.commons.livexp.util.ExceptionUtil;
import reactor.core.Disposable;
public class CloudFoundryApplicationHarness extends AbstractDisposable {
private Set<String> ownedAppNames = new HashSet<>();
private DefaultClientRequestsV2 client;
public CloudFoundryApplicationHarness(DefaultClientRequestsV2 client) {
this.client = client;
if (client!=null) {
onDispose((d) -> { deleteOwnedApps(); });
}
}
public String randomAppName() throws Exception {
String name = StringUtil.datestamp()+"-"+randomAlphabetic(10);
ownedAppNames.add(name);
streamOutput(name);
return name;
}
private void streamOutput(String name) throws Exception {
if (client!=null) {
IApplicationLogConsole logConsole = new IApplicationLogConsole() {
@Override
public void onMessage(LogMessage log) {
System.out.println("%"+name+"-out: "+log.getMessage());
}
@Override
public void onComplete() {
System.out.println("%"+name+"-COMPLETE");
}
@Override
public void onError(Throwable exception) {
System.out.println("%"+name+"-ERROR: "+ExceptionUtil.getMessage(exception));
}
};
Disposable logToken = client.streamLogs(name, logConsole);
onDispose((d) -> {
logToken.dispose();
});
}
}
protected void deleteOwnedApps() {
System.out.println("owned app names: "+ownedAppNames);
if (!ownedAppNames.isEmpty()) {
try {
for (String name : ownedAppNames) {
try {
System.out.println("delete owned app: "+name);
this.client.deleteApplication(name);
} catch (Exception e) {
System.out.println("Delete failed: " +ExceptionUtil.getMessage(e));
// May get 404 or other 400 errors if it is alrready
// gone so don't prevent other owned apps from being
// deleted
}
}
} catch (Exception e) {
fail("failed to cleanup owned apps: " + e.getMessage());
}
}
}
}

View File

@@ -1,606 +0,0 @@
/*******************************************************************************
* Copyright (c) 2015 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.contains;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.ide.eclipse.boot.dash.test.BootDashModelTest.waitForJobsToComplete;
import static org.springframework.ide.eclipse.boot.dash.test.CloudFoundryTestHarness.APP_DELETE_TIMEOUT;
import static org.springframework.ide.eclipse.boot.dash.test.CloudFoundryTestHarness.APP_DEPLOY_TIMEOUT;
import static org.springframework.ide.eclipse.boot.dash.test.CloudFoundryTestHarness.APP_IS_VISIBLE_TIMEOUT;
import static org.springframework.ide.eclipse.boot.dash.test.CloudFoundryTestHarness.SERVICE_DELETE_TIMEOUT;
import static org.springframework.ide.eclipse.boot.dash.test.util.JobUtil.runInJob;
import static org.springframework.ide.eclipse.boot.test.BootProjectTestHarness.withStarters;
import static org.springsource.ide.eclipse.commons.tests.util.StsTestCase.createFile;
import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.commons.io.IOUtils;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Assert;
import org.eclipse.debug.core.DebugPlugin;
import org.junit.After;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFClientParams;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFCredentials;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFServiceInstance;
import org.springframework.ide.eclipse.boot.dash.cf.client.ClientRequests;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFCredentials.CFCredentialType;
import org.springframework.ide.eclipse.boot.dash.cf.client.v2.DefaultClientRequestsV2;
import org.springframework.ide.eclipse.boot.dash.cf.client.v2.DefaultCloudFoundryClientFactoryV2;
import org.springframework.ide.eclipse.boot.dash.cf.dialogs.StoreCredentialsMode;
import org.springframework.ide.eclipse.boot.dash.cf.model.CloudAppDashElement;
import org.springframework.ide.eclipse.boot.dash.cf.model.CloudFoundryBootDashModel;
import org.springframework.ide.eclipse.boot.dash.cf.model.CloudServiceInstanceDashElement;
import org.springframework.ide.eclipse.boot.dash.model.BootDashElement;
import org.springframework.ide.eclipse.boot.dash.model.BootProjectDashElement;
import org.springframework.ide.eclipse.boot.dash.model.RunState;
import org.springframework.ide.eclipse.boot.dash.model.UserInteractions;
import org.springframework.ide.eclipse.boot.dash.test.util.SslValidationDisabler;
import org.springframework.ide.eclipse.boot.test.AutobuildingEnablement;
import org.springframework.ide.eclipse.boot.test.BootProjectTestHarness;
import org.springframework.ide.eclipse.boot.test.util.TestBracketter;
import org.springsource.ide.eclipse.commons.core.util.StringUtil;
import org.springsource.ide.eclipse.commons.frameworks.test.util.ACondition;
import org.springsource.ide.eclipse.commons.tests.util.StsTestUtil;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
/**
* @author Kris De Volder
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class CloudFoundryBootDashModelIntegrationTest {
private TestBootDashModelContext context;
private BootProjectTestHarness projects;
private CloudFoundryTestHarness harness;
////////////////////////////////////////////////////////////
private CFClientParams clientParams = CfTestTargetParams.fromEnv();
private DefaultCloudFoundryClientFactoryV2 clientFactory = DefaultCloudFoundryClientFactoryV2.INSTANCE;
private DefaultClientRequestsV2 client = CloudFoundryClientTest.createClient(clientParams);
public CloudFoundryApplicationHarness appHarness = new CloudFoundryApplicationHarness(client);
@Rule
public AutobuildingEnablement disableAutoBuild = new AutobuildingEnablement(false);
@Rule
public TestBracketter testBracketter = new TestBracketter();
public CloudFoundryServicesHarness services = new CloudFoundryServicesHarness(clientParams, client);
@Before
public void setup() throws Exception {
SslValidationDisabler.disableSslValidation();
StsTestUtil.deleteAllProjects();
this.context = new TestBootDashModelContext(
ResourcesPlugin.getWorkspace(),
DebugPlugin.getDefault().getLaunchManager()
).withCfClient(clientFactory);
this.harness = CloudFoundryTestHarness.create(context);
this.projects = new BootProjectTestHarness(context.getWorkspace());
}
@After
public void tearDown() throws Exception {
appHarness.deleteOwnedApps();
services.dispose();
client.close();
harness.dispose();
}
////////////////////////////////////////////////////////////
@Test
public void testCreateCfTarget() throws Exception {
CloudFoundryBootDashModel target = harness.createCfTarget(CfTestTargetParams.fromEnv());
CFCredentials credentials = target.getRunTarget().getTargetProperties().getCredentials();
assertNotNull(target);
assertEquals(CFCredentialType.PASSWORD, credentials.getType());
assertNotNull(credentials.getSecret());
assertEquals(1, harness.getCfRunTargetModels().size());
}
@Test public void refreshTokenStreamTerminatedOnDispose() throws Exception {
CFClientParams params = CfTestTargetParams.fromEnv();
ClientRequests client = clientFactory.getClient(params);
Future<List<String>> tokens = runInJob(() -> {
return client.getRefreshTokens().collect(Collectors.toList()).block();
});
client.getApplicationsWithBasicInfo(); // forces the client to authenticate
client.dispose();
assertEquals(1, tokens.get(2, TimeUnit.SECONDS).size());
}
@Test public void testCreateCfTargetAndStoreToken() throws Exception {
CFClientParams targetParams = CfTestTargetParams.fromEnv();
CloudFoundryBootDashModel target = harness.createCfTarget(targetParams, StoreCredentialsMode.STORE_TOKEN);
assertNotNull(target);
assertTrue(target.isConnected());
CFCredentials credentials = target.getRunTarget().getTargetProperties().getCredentials();
assertEquals(CFCredentialType.REFRESH_TOKEN, credentials.getType());
assertNotNull(credentials.getSecret());
assertEquals(1, harness.getCfRunTargetModels().size());
}
/**
* Test that tests a bunch of things.
* TODO: It isn't good practice to create 'test everything' tests...
* but we do it anyway because ramping up a test that deploys an app takes about 90 seconds...
* Maybe we can factor this better somehow so we have separate tests, but only deploy app once?
*/
@Test
public void testDeployAppAndDeleteAndStuff() throws Exception {
harness.createCfTarget(CfTestTargetParams.fromEnv());
final CloudFoundryBootDashModel model = harness.getCfTargetModel();
final BootProjectDashElement project = harness.getElementFor(
projects.createBootProject("to-deploy", withStarters("actuator", "web"))
);
final String appName = appHarness.randomAppName();
harness.answerDeploymentPrompt(ui(), appName, appName);
model.add(ImmutableList.<Object>of(project));
//The resulting deploy is asynchronous
new ACondition("wait for app '"+ appName +"'to appear", APP_IS_VISIBLE_TIMEOUT) {
public boolean test() throws Exception {
assertNotNull(model.getApplication(appName));
return true;
}
};
new ACondition("wait for app '"+ appName +"'to be RUNNING", APP_DEPLOY_TIMEOUT) {
public boolean test() throws Exception {
CloudAppDashElement element = model.getApplication(appName);
assertEquals(RunState.RUNNING, element.getRunState());
return true;
}
};
//Try to get request mappings
//TODO: make this work again in recent boot version (the rm endpoints are now not accessible anymore over http/https by default
// must actuator + ssh tunnel
// new ACondition("wait for request mappings", FETCH_REQUEST_MAPPINGS_TIMEOUT) {
// public boolean test() throws Exception {
// CloudAppDashElement element = model.getApplication(appName);
// List<RequestMapping> mappings = element.getLiveRequestMappings();
// assertNotNull(mappings); //Why is the test sometimes failing here?
// assertTrue(!mappings.isEmpty()); //Even though this is an 'empty' app should have some mappings,
// // for example an 'error' page.
// return true;
// }
// };
//Try to delete the app...
reset(ui());
when(ui().confirmOperation(eq("Deleting Elements"), anyString())).thenReturn(true);
CloudAppDashElement app = model.getApplication(appName);
app.getBootDashModel().delete(ImmutableList.<BootDashElement>of(app), ui());
new ACondition("wait for app to be deleted", APP_DELETE_TIMEOUT) {
@Override
public boolean test() throws Exception {
assertNull(model.getApplication(appName));
return true;
}
};
}
private AllUserInteractions ui() {
return context.injections.getBean(AllUserInteractions.class);
}
@Test public void testDeployAppIntoDebugMode() throws Exception {
harness.createCfTarget(CfTestTargetParams.fromEnv());
final CloudFoundryBootDashModel model = harness.getCfTargetModel();
final BootProjectDashElement project = harness.getElementFor(
projects.createBootProject("to-deploy", withStarters("actuator", "web"))
);
final String appName = appHarness.randomAppName();
harness.answerDeploymentPrompt(ui(), appName, appName);
model.performDeployment(ImmutableSet.of(project.getProject()), RunState.DEBUGGING);
new ACondition("wait for app '"+ appName +"'to be DEBUGGING", APP_DEPLOY_TIMEOUT) {
public boolean test() throws Exception {
CloudAppDashElement element = model.getApplication(appName);
assertEquals(RunState.DEBUGGING, element.getRunState());
return true;
}
};
}
//This test commented because it uses 'createApplication' which no longer exists in V2 client.
// @Test
// public void testPreexistingApplicationInModel() throws Exception {
// // Create external client and deploy app "externally"
// ClientRequests externalClient = harness.createExternalClient(CfTestTargetParams.fromEnv());
//
// List<CFCloudDomain> domains = externalClient.getDomains();
//
// final String preexistingAppName = harness.randomAppName();
//
// CloudApplicationDeploymentProperties deploymentProperties = new CloudApplicationDeploymentProperties();
// deploymentProperties.setAppName(preexistingAppName);
// deploymentProperties.setMemory(1024);
// deploymentProperties.setUris(ImmutableList.of(preexistingAppName + "." + domains.get(0).getName()));
// deploymentProperties.setServices(ImmutableList.<String>of());
// externalClient.createApplication(deploymentProperties);
//
// // Create the boot dash target and model
// harness.createCfTarget(CfTestTargetParams.fromEnv());
//
// final CloudFoundryBootDashModel model = harness.getCfTargetModel();
//
// final BootProjectDashElement project = harness
// .getElementFor(projects.createBootWebProject("testPreexistingApplicationInModel"));
// final String newAppName = harness.randomAppName();
//
// // Create a new one too
// harness.answerDeploymentPrompt(ui(), newAppName, newAppName);
//
// model.add(ImmutableList.<Object> of(project), ui);
//
// // The resulting deploy is asynchronous
// new ACondition("wait for apps '" + newAppName + "' and '" + preexistingAppName + "' to appear",
// APP_IS_VISIBLE_TIMEOUT) {
// public boolean test() throws Exception {
// assertNotNull(model.getApplication(newAppName));
// assertNotNull(model.getApplication(preexistingAppName));
//
// // check project mapping
// assertEquals("Expected new element in model to have workspace project mapping",
// model.getApplication(newAppName).getProject(), project.getProject());
//
// // No project mapping for the "external" app
// assertNull(model.getApplication(preexistingAppName).getProject());
//
// // check the actual CloudApplication
// CFApplication actualNewApp = model.getApplication(newAppName).getSummaryData();
// assertEquals("No CloudApplication mapping found", actualNewApp.getName(), newAppName);
//
// CFApplication actualPreexistingApp = model.getApplication(preexistingAppName).getSummaryData();
// assertEquals("No CloudApplication mapping found", actualPreexistingApp.getName(), preexistingAppName);
//
// return true;
// }
// };
// }
@Test
public void testEnvVarsSetOnFirstDeploy() throws Exception {
CloudFoundryBootDashModel target = harness.createCfTarget(CfTestTargetParams.fromEnv());
final CloudFoundryBootDashModel model = harness.getCfTargetModel();
IProject project = projects.createBootProject("to-deploy", withStarters("actuator", "web"));
final String appName = appHarness.randomAppName();
Map<String, String> env = new HashMap<>();
env.put("FOO", "something");
harness.answerDeploymentPrompt(ui(), appName, appName, env);
model.performDeployment(ImmutableSet.of(project), RunState.RUNNING);
new ACondition("wait for app '"+ appName +"'to be RUNNING", APP_DEPLOY_TIMEOUT) {
public boolean test() throws Exception {
CloudAppDashElement element = model.getApplication(appName);
assertEquals(RunState.RUNNING, element.getRunState());
return true;
}
};
Map<String,String> actualEnv = harness.fetchEnvironment(target, appName);
assertEquals("something", actualEnv.get("FOO"));
}
@Test
public void testServicesBoundOnFirstDeploy() throws Exception {
CloudFoundryBootDashModel target = harness.createCfTarget(CfTestTargetParams.fromEnv());
final CloudFoundryBootDashModel model = harness.getCfTargetModel();
IProject project = projects.createBootProject("to-deploy", withStarters("actuator", "web"));
List<String> bindServices = ImmutableList.of(
services.createTestService(), services.createTestService()
);
ACondition.waitFor("services exist "+bindServices, 30_000, () -> {
Set<String> services = client.getServices().stream()
.map(CFServiceInstance::getName)
.collect(Collectors.toSet());
System.out.println("services = "+services);
assertTrue(services.containsAll(bindServices));
});
final String appName = appHarness.randomAppName();
harness.answerDeploymentPrompt(ui(), appName, appName, bindServices);
model.performDeployment(ImmutableSet.of(project), RunState.RUNNING);
new ACondition("wait for app '"+ appName +"'to be RUNNING", APP_DEPLOY_TIMEOUT) {
public boolean test() throws Exception {
CloudAppDashElement element = model.getApplication(appName);
assertEquals(RunState.RUNNING, element.getRunState());
return true;
}
};
Set<String> actualServices = client.getBoundServicesSet(appName).block();
assertEquals(ImmutableSet.copyOf(bindServices), actualServices);
}
@Test public void testDeployManifestWithAbsolutePathAttribute() throws Exception {
CFClientParams targetParams = CfTestTargetParams.fromEnv();
IProject project = projects.createProject("to-deploy");
CloudFoundryBootDashModel model = harness.createCfTarget(targetParams);
waitForJobsToComplete();
File zipFile = getTestZip("testapp");
final String appName = appHarness.randomAppName();
IFile manifestFile = createFile(project, "manifest.yml",
"applications:\n" +
"- name: "+appName+"\n" +
" path: "+zipFile.getAbsolutePath() + "\n" +
" buildpack: staticfile_buildpack\n"
);
harness.answerDeploymentPrompt(ui(), manifestFile);
model.performDeployment(ImmutableSet.of(project), RunState.RUNNING);
ACondition.waitFor("app to appear", APP_IS_VISIBLE_TIMEOUT, () -> {
assertNotNull(model.getApplication(appName));
});
CloudAppDashElement app = model.getApplication(appName);
ACondition.waitFor("app to be running", APP_DEPLOY_TIMEOUT, () -> {
assertEquals(RunState.RUNNING, app.getRunState());
String url = pathJoin(app.getUrl(),"test.txt");
assertEquals(url, "some content here\n", IOUtils.toString(new URL(url)));
});
verify(ui()).promptApplicationDeploymentProperties(any());
verifyNoMoreInteractions(ui());
}
@Test public void randomRoute() throws Exception {
CFClientParams targetParams = CfTestTargetParams.fromEnv();
IProject project = projects.createBootProject("to-deploy", withStarters("actuator", "web"));
CloudFoundryBootDashModel model = harness.createCfTarget(targetParams);
waitForJobsToComplete();
final String appName = appHarness.randomAppName();
IFile manifestFile = createFile(project, "manifest.yml",
"applications:\n" +
"- name: "+appName+"\n" +
" random-route: true\n" +
" buildpack: java_buildpack\n" +
" env:\n" +
" JBP_CONFIG_OPEN_JDK_JRE: '{ \"jre\": { version: 11.+ } }'\n"
);
harness.answerDeploymentPrompt(ui(), manifestFile);
model.performDeployment(ImmutableSet.of(project), RunState.RUNNING);
ACondition.waitFor("app to appear", APP_IS_VISIBLE_TIMEOUT, () -> {
assertNotNull(model.getApplication(appName));
});
CloudAppDashElement app = model.getApplication(appName);
ACondition.waitFor("app to be running", APP_DEPLOY_TIMEOUT, () -> {
assertEquals(RunState.RUNNING, app.getRunState());
});
String host = app.getLiveHost();
assertTrue("app has host", StringUtil.hasText(host));
assertTrue("app has default domain", host.endsWith("."+CFAPPS_IO()));
host = host.substring(0, host.length()-CFAPPS_IO().length()-1);
assertTrue("host is random generated on push", !host.equals(appName));
}
private String CFAPPS_IO() {
return CloudFoundryClientTest.get_CFAPPS_IO(clientParams);
}
@Test public void randomRouteWithDomain() throws Exception {
CFClientParams targetParams = CfTestTargetParams.fromEnv();
IProject project = projects.createBootProject("to-deploy", withStarters("actuator", "web"));
CloudFoundryBootDashModel model = harness.createCfTarget(targetParams);
waitForJobsToComplete();
final String appName = appHarness.randomAppName();
IFile manifestFile = createFile(project, "manifest.yml",
"applications:\n" +
"- name: "+appName+"\n" +
" domain: "+CFAPPS_IO() + "\n" +
" random-route: true\n" +
" buildpack: java_buildpack\n" +
" env:\n" +
" JBP_CONFIG_OPEN_JDK_JRE: '{ \"jre\": { version: 11.+ } }'\n"
);
harness.answerDeploymentPrompt(ui(), manifestFile);
model.performDeployment(ImmutableSet.of(project), RunState.RUNNING);
ACondition.waitFor("app to appear", APP_IS_VISIBLE_TIMEOUT, () -> {
assertNotNull(model.getApplication(appName));
});
CloudAppDashElement app = model.getApplication(appName);
ACondition.waitFor("app to be running", APP_DEPLOY_TIMEOUT, () -> {
assertEquals(RunState.RUNNING, app.getRunState());
});
String host = app.getLiveHost();
assertTrue("app has host", StringUtil.hasText(host));
assertTrue("app has default domain", host.endsWith("."+CFAPPS_IO()));
host = host.substring(0, host.length()-CFAPPS_IO().length()-1);
assertTrue("host is random generated on push", !host.equals(appName));
}
@Test public void httpRoute() throws Exception {
CFClientParams targetParams = CfTestTargetParams.fromEnv();
IProject project = projects.createBootProject("to-deploy", withStarters("actuator", "web"));
CloudFoundryBootDashModel model = harness.createCfTarget(targetParams);
waitForJobsToComplete();
final String appName = appHarness.randomAppName();
IFile manifestFile = createFile(project, "manifest.yml",
"applications:\n" +
"- name: "+appName+"\n" +
" buildpack: java_buildpack\n" +
" env:\n" +
" JBP_CONFIG_OPEN_JDK_JRE: '{ \"jre\": { version: 11.+ } }'\n" +
" routes:\n" +
" - route: " + appName + '.'+CFAPPS_IO()
);
harness.answerDeploymentPrompt(ui(), manifestFile);
model.performDeployment(ImmutableSet.of(project), RunState.RUNNING);
ACondition.waitFor("app to appear", APP_IS_VISIBLE_TIMEOUT, () -> {
assertNotNull(model.getApplication(appName));
});
CloudAppDashElement app = model.getApplication(appName);
ACondition.waitFor("app to be running", APP_DEPLOY_TIMEOUT, () -> {
assertEquals(RunState.RUNNING, app.getRunState());
});
String host = app.getLiveHost();
assertEquals(appName + '.'+CFAPPS_IO(), host);
}
@Ignore
@Test public void httpRouteWithPath() throws Exception {
// This fails because the path part is not obtained from element. Bug already raised
CFClientParams targetParams = CfTestTargetParams.fromEnv();
IProject project = projects.createBootProject("to-deploy", withStarters("actuator", "web"));
CloudFoundryBootDashModel model = harness.createCfTarget(targetParams);
waitForJobsToComplete();
final String appName = appHarness.randomAppName();
IFile manifestFile = createFile(project, "manifest.yml",
"applications:\n" +
"- name: "+appName+"\n" +
" buildpack: java_buildpack\n" +
" env:\n" +
" JBP_CONFIG_OPEN_JDK_JRE: '{ \"jre\": { version: 11.+ } }'\n" +
" routes:\n" +
" - route: " + appName + '.'+CFAPPS_IO() + "/myapppath"
);
harness.answerDeploymentPrompt(ui(), manifestFile);
model.performDeployment(ImmutableSet.of(project), RunState.RUNNING);
ACondition.waitFor("app to appear", APP_IS_VISIBLE_TIMEOUT, () -> {
assertNotNull(model.getApplication(appName));
});
CloudAppDashElement app = model.getApplication(appName);
ACondition.waitFor("app to be running", APP_DEPLOY_TIMEOUT, () -> {
assertEquals(RunState.RUNNING, app.getRunState());
});
String host = app.getLiveHost();
assertEquals(appName + '.'+CFAPPS_IO()+ "/myapppath", host);
}
private String pathJoin(String url, String append) {
while (url.endsWith("/")) {
url = url.substring(0, url.length()-1);
}
while (append.startsWith("/")) {
append = append.substring(1);
}
return url+"/"+append;
}
@Test public void deleteService() throws Exception {
String serviceName = services.createTestService();
CFClientParams targetParams = CfTestTargetParams.fromEnv();
CloudFoundryBootDashModel model = harness.createCfTarget(targetParams);
ACondition.waitFor("service to appear", APP_IS_VISIBLE_TIMEOUT, () -> {
assertNotNull(model.getService(serviceName));
});
when(ui().confirmOperation(contains("Deleting"), contains("Are you sure that you want to delete")))
.thenReturn(true);
CloudServiceInstanceDashElement service = model.getService(serviceName);
model.canDelete(service);
model.delete(ImmutableSet.of(service), ui());
ACondition.waitFor("service to disapear", SERVICE_DELETE_TIMEOUT, () -> {
assertNull(model.getService(serviceName));
});
}
///////////////////////////////////////////////////////////////////////////////////
private File getTestZip(String fileName) {
File sourceWorkspace = new File(
StsTestUtil.getSourceWorkspacePath("org.springframework.ide.eclipse.boot.dash.test"));
File file = new File(sourceWorkspace, fileName + ".zip");
Assert.isTrue(file.exists(), ""+ file);
return file;
}
}

View File

@@ -1,118 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.springframework.ide.eclipse.boot.dash.test.CloudFoundryClientTest.FLAKY_SERVICE_BROKER;
import java.time.Duration;
import java.util.HashSet;
import java.util.Set;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFClientParams;
import org.springframework.ide.eclipse.boot.dash.cf.client.v2.DefaultClientRequestsV2;
import org.springframework.ide.eclipse.boot.util.RetryUtil;
import org.springsource.ide.eclipse.commons.core.util.StringUtil;
import org.springsource.ide.eclipse.commons.livexp.ui.Disposable;
import org.springsource.ide.eclipse.commons.livexp.util.ExceptionUtil;
import com.google.common.collect.ImmutableMap;
public class CloudFoundryServicesHarness implements Disposable {
public static final Duration CREATE_SERVICE_TIMEOUT = Duration.ofMinutes(1);
private static final Duration DELETE_SERVICE_TIMEOUT = Duration.ofMinutes(1);
private DefaultClientRequestsV2 client;
private CFClientParams clientParams;
public CloudFoundryServicesHarness(CFClientParams clientParams, DefaultClientRequestsV2 client) {
this.client = client;
this.clientParams = clientParams;
}
private Set<String> ownedServiceNames = new HashSet<>();
public String[] getTestServiceAndPlan() {
String org = clientParams.getOrgName();
String api = clientParams.getApiUrl();
if (org.equals("application-platform-testing")) {
//PWS test space/org
return new String[] {"cloudamqp", "lemur"};
} else if (api.contains("api.run.pez.")) {
//PEZ
return new String[] {"p-rabbitmq", "standard"};
} else if (api.contains("api.tan.")) {
//TAN RGB
//return new String[] {"app-autoscaler", "bronze"}; //Warning not good enough for some tests!
return new String[] {"p-rabbitmq", "standard"};
} else if (api.contains("wdc-06-pcf2-system.oc.vmware.com")) {
return new String[] {"p-rabbitmq", "standard"};
}
return null;
}
public String randomServiceName() {
String name = StringUtil.datestamp()+"-"+randomAlphabetic(10);
ownedServiceNames.add(name);
return name;
}
public String createTestUserProvidedService() {
String name = randomServiceName();
client.createUserProvidedService(name, ImmutableMap.of()).block(CREATE_SERVICE_TIMEOUT);
return name;
}
public String createTestService() throws Exception {
String name = randomServiceName();
RetryUtil.retryWhen("createTestService["+name+"]", 5, FLAKY_SERVICE_BROKER, () -> {
String[] serviceParams = getTestServiceAndPlan();
client.createService(name, serviceParams[0], serviceParams[1]).block(CREATE_SERVICE_TIMEOUT);
});
return name;
}
protected void deleteOwnedServices() {
if (!ownedServiceNames.isEmpty()) {
System.out.println("owned services: "+ownedServiceNames);
try {
for (String serviceName : ownedServiceNames) {
System.out.println("delete service: "+serviceName);
try {
RetryUtil.retryTimes("delete sercice "+serviceName, 3, () -> {
this.client.deleteServiceAsync(serviceName).block(DELETE_SERVICE_TIMEOUT);
});
} catch (Exception e) {
System.out.println("Failed to delete ["+serviceName+"]: "+ExceptionUtil.getMessage(e));
// May get 404 or other 400 errors if it is alrready
// gone so don't prevent other owned apps from being
// deleted
}
}
} catch (Exception e) {
fail("failed to cleanup owned services: " + e.getMessage());
}
}
}
@Override
public void dispose() {
assertTrue(!client.isLoggedOut());
deleteOwnedServices();
}
}

View File

@@ -1,387 +0,0 @@
/*******************************************************************************
* Copyright (c) 2015, 2019 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.apache.commons.io.IOUtils;
import org.eclipse.core.resources.IFile;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.ide.eclipse.boot.dash.api.RunTargetType;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFClientParams;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFSpace;
import org.springframework.ide.eclipse.boot.dash.cf.client.CloudFoundryClientFactory;
import org.springframework.ide.eclipse.boot.dash.cf.deployment.CloudApplicationDeploymentProperties;
import org.springframework.ide.eclipse.boot.dash.cf.dialogs.CloudFoundryTargetWizardModel;
import org.springframework.ide.eclipse.boot.dash.cf.dialogs.DeploymentPropertiesDialogModel;
import org.springframework.ide.eclipse.boot.dash.cf.dialogs.PasswordDialogModel;
import org.springframework.ide.eclipse.boot.dash.cf.dialogs.StoreCredentialsMode;
import org.springframework.ide.eclipse.boot.dash.cf.jmxtunnel.JmxSshTunnelManager;
import org.springframework.ide.eclipse.boot.dash.cf.model.CloudFoundryBootDashModel;
import org.springframework.ide.eclipse.boot.dash.cf.runtarget.CloudFoundryRunTarget;
import org.springframework.ide.eclipse.boot.dash.cf.runtarget.CloudFoundryRunTargetType;
import org.springframework.ide.eclipse.boot.dash.cf.ui.CfUserInteractions;
import org.springframework.ide.eclipse.boot.dash.dialogs.ManifestDiffDialogModel;
import org.springframework.ide.eclipse.boot.dash.model.BootDashModel;
import org.springframework.ide.eclipse.boot.dash.model.LocalBootDashModel;
import org.springframework.ide.eclipse.boot.dash.model.RunTarget;
import org.springframework.ide.eclipse.boot.dash.model.SecuredCredentialsStore;
import org.springframework.ide.eclipse.boot.dash.model.UserInteractions;
import org.springframework.ide.eclipse.boot.dash.model.runtargettypes.RunTargetTypes;
import org.springframework.ide.eclipse.boot.dash.test.mocks.MockRunnableContext;
import org.springsource.ide.eclipse.commons.core.pstore.IPropertyStore;
import org.springsource.ide.eclipse.commons.frameworks.test.util.ACondition;
import org.springsource.ide.eclipse.commons.frameworks.test.util.Asserter1;
import com.google.common.collect.ImmutableSet;
/**
* @author Kris De Volder
*/
public class CloudFoundryTestHarness extends BootDashViewModelHarness {
@FunctionalInterface
public interface MultipleChoiceAnswerer {
int apply(String title, String msg, String[] choices, int defaultIndex);
}
public static class DeploymentAnswerer {
String yaml;
String appName;
public DeploymentAnswerer(String yaml, String appName) {
this.yaml = yaml;
this.appName = appName;
}
public DeploymentAnswerer(String yaml) {
this(yaml, null);
}
public DeploymentAnswerer() {
this(null, null);
}
public void apply(CloudApplicationDeploymentProperties deploymentProperties) throws Exception {};
}
@FunctionalInterface
public interface PasswordAnswerer {
void apply(PasswordDialogModel model) throws Exception;
}
/**
* How long to wait for deleted app to disapear from the model.
*/
public static final long APP_DELETE_TIMEOUT = TimeUnit.MINUTES.toMillis(1);
/**
* How long to wait for deleted app to disapear from the model.
*/
public static final long SERVICE_DELETE_TIMEOUT = TimeUnit.MINUTES.toMillis(1);
/**
* How long to wait for a deployed app to show up in the model? This should
* be relatively short.
*/
public static final long APP_IS_VISIBLE_TIMEOUT = 20_000;
/**
* How long to wait for a deployed app to transition to running state.
*/
public static final long APP_DEPLOY_TIMEOUT = TimeUnit.MINUTES.toMillis(6);
/**
* How long to wait on retrieving request mappings from a CF app.
*/
public static final long FETCH_REQUEST_MAPPINGS_TIMEOUT = 5_000;
/**
* How long to wait for runtarget to become 'connected'.
*/
public static final long CONNECT_TARGET_TIMEOUT = 30_000;
public static CloudFoundryTestHarness create(TestBootDashModelContext context) throws Exception {
context.injections.assertDefinitionFor(CloudFoundryClientFactory.class);
context.injections.assertNoDefinitionFor(RunTargetType.class);
context.injections.defInstance(RunTargetType.class, RunTargetTypes.LOCAL);
context.injections.def(CloudFoundryRunTargetType.class, CloudFoundryRunTargetType::new);
return new CloudFoundryTestHarness(context);
}
public CloudFoundryBootDashModel getCfTargetModel() {
return (CloudFoundryBootDashModel) getRunTargetModel(cfTargetType());
}
private RunTargetType cfTargetType() {
List<RunTargetType> types = context.injections.getBeans(RunTargetType.class);
for (RunTargetType t : types) {
if (t instanceof CloudFoundryRunTargetType) {
return t;
}
}
throw new NoSuchElementException("No cf target type");
}
private CloudFoundryClientFactory clientFactory() {
return context.injections.getBean(CloudFoundryClientFactory.class);
}
public CloudFoundryBootDashModel createCfTarget(
CFClientParams params,
StoreCredentialsMode storePassword
) throws Exception {
return createCfTarget(params, storePassword, (wizard) -> assertOk(wizard.getValidator()));
}
public CloudFoundryBootDashModel createCfTarget(
CFClientParams params,
StoreCredentialsMode storePassword,
Asserter1<CloudFoundryTargetWizardModel> wizardAsserter
) throws Exception {
CloudFoundryTargetWizardModel wizard = new CloudFoundryTargetWizardModel(cfTargetType(), clientFactory(), NO_TARGETS, context);
wizard.setUrl(params.getApiUrl());
wizard.setUsername(params.getUsername());
wizard.setStoreCredentials(storePassword);
wizard.setMethod(params.getCredentials().getType().toLoginMethod());
wizard.setPassword(params.getCredentials().getSecret());
wizard.setSelfsigned(params.isSelfsigned());
wizard.skipSslValidation(params.skipSslValidation());
wizard.resolveSpaces(new MockRunnableContext());
assertNotNull(wizard.getRefreshToken());
wizard.setSpace(getSpace(wizard, params.getOrgName(), params.getSpaceName()));
wizardAsserter.execute(wizard);
final CloudFoundryRunTarget newTarget = wizard.finish();
if (newTarget!=null) {
model.getRunTargets().add(newTarget);
}
final CloudFoundryBootDashModel targetModel = getCfModelFor(newTarget);
//The created targetModel automatically connected, but this happens asynchly.
new ACondition("Wait for connected state", CONNECT_TARGET_TIMEOUT) {
public boolean test() throws Exception {
return targetModel.isConnected();
}
};
return targetModel;
}
public CloudFoundryBootDashModel createCfTarget(CFClientParams params) throws Exception {
return createCfTarget(params, StoreCredentialsMode.STORE_PASSWORD);
}
public CloudFoundryBootDashModel getCfModelFor(CloudFoundryRunTarget cfTarget) {
return (CloudFoundryBootDashModel) model.getSectionByTargetId(cfTarget.getId());
}
private static final ImmutableSet<RunTarget> NO_TARGETS = ImmutableSet.of();
private CloudFoundryTestHarness(TestBootDashModelContext context) throws Exception {
super(context);
context.injections.assertDefinitionFor(CloudFoundryRunTargetType.class);
context.injections.assertDefinitionFor(CloudFoundryClientFactory.class);
}
private static CFSpace getSpace(CloudFoundryTargetWizardModel wizard, String orgName, String spaceName) {
for (CFSpace space : wizard.getSpaces().getOrgSpaces(orgName)) {
if (space.getName().equals(spaceName)) {
return space;
}
}
fail("Not found org/space = "+orgName+"/"+spaceName);
return null;
}
public void answerDeploymentPrompt(CfUserInteractions ui, final String appName, final String hostName) throws Exception {
final String yaml = "applications:\n" +
"- name: "+appName+"\n" +
" host: "+hostName+"\n" +
" env:\n" +
" JBP_CONFIG_OPEN_JDK_JRE: '{ \"jre\": { version: 11.+ } }'\n";
answerDeploymentPrompt(ui, new DeploymentAnswerer(yaml));
}
public void answerConfirmationMultipleChoice(UserInteractions ui, MultipleChoiceAnswerer answerer) {
doAnswer(new Answer<Integer>() {
@Override
public Integer answer(InvocationOnMock invocation) throws Throwable {
// int confirmOperation(String title, String message, String[] buttonLabels, int defaultButtonIndex);
String title = (String) invocation.getArguments()[0];
String msg = (String) invocation.getArguments()[1];
String[] choices = (String[]) invocation.getArguments()[2];
int defaultIndex = (int) invocation.getArguments()[3];
return answerer.apply(title, msg, choices, defaultIndex);
}
})
.when(ui)
.confirmOperation(any(), any(), any(), anyInt());
}
public void answerDeploymentPrompt(CfUserInteractions ui, final String appName, final String hostName, final List<String> bindServices) throws Exception {
//TODO: replace this method with something more 'generic' that accepts a function which is passed the deploymentProperties
// so that it can add additional infos to it.
final String yaml = "applications:\n" +
"- name: "+appName+"\n" +
" host: "+hostName+"\n" +
" env:\n" +
" JBP_CONFIG_OPEN_JDK_JRE: '{ \"jre\": { version: 11.+ } }'\n" +
createServicesBlock(bindServices);
answerDeploymentPrompt(ui, new DeploymentAnswerer(yaml));
}
private String createServicesBlock(List<String> bindServices) {
if (bindServices==null || bindServices.isEmpty()) {
return "";
}
StringBuilder buf = new StringBuilder(" services:\n");
for (String s : bindServices) {
buf.append(" - "+s+"\n");
}
return buf.toString();
}
private String createEnvBlock(Map<String, String> env) {
if (env==null || env.isEmpty()) {
return " env:\n" +
" JBP_CONFIG_OPEN_JDK_JRE: '{ \"jre\": { version: 11.+ } }'\n";
}
StringBuilder buf = new StringBuilder(
" env:\n" +
" JBP_CONFIG_OPEN_JDK_JRE: '{ \"jre\": { version: 11.+ } }'\n"
);
for (Entry<String, String> e : env.entrySet()) {
buf.append(" "+e.getKey()+": "+e.getValue());
}
return buf.toString();
}
public void answerDeploymentPrompt(CfUserInteractions ui, final String appName, final String hostName, final Map<String,String> env) throws Exception {
String yaml = "applications:\n" +
"- name: "+appName+"\n" +
" host: "+hostName+"\n" +
createEnvBlock(env);
answerDeploymentPrompt(ui, new DeploymentAnswerer(yaml));
}
/**
* Does the same thing as what would happen if a user answered the deployment props dialog by selecting an
* existing manifest file.
*/
public void answerDeploymentPrompt(CfUserInteractions ui, IFile manifestToSelect) throws Exception {
String yaml = IOUtils.toString(manifestToSelect.getContents(), manifestToSelect.getCharset());
answerDeploymentPrompt(ui, new DeploymentAnswerer(yaml) {
@Override
public void apply(CloudApplicationDeploymentProperties properties) throws Exception {
properties.setManifestFile(manifestToSelect);
}
});
}
public void answerDeploymentPrompt(CfUserInteractions ui, DeploymentAnswerer answerer) throws Exception {
when(ui.promptApplicationDeploymentProperties(any(DeploymentPropertiesDialogModel.class)))
.thenAnswer(new Answer<CloudApplicationDeploymentProperties>() {
@Override
public CloudApplicationDeploymentProperties answer(InvocationOnMock invocation) throws Throwable {
DeploymentPropertiesDialogModel dialog = (DeploymentPropertiesDialogModel) invocation.getArguments()[0];
CloudApplicationDeploymentProperties deploymentProperties = dialog.getDeploymentProperties(answerer.yaml, answerer.appName);
answerer.apply(deploymentProperties);
return deploymentProperties;
}
});
}
public String privateStoreKey(CloudFoundryBootDashModel target) {
return secureStoreKey(target)+":token";
}
public String secureStoreKey(CloudFoundryBootDashModel target) {
return target.getRunTarget().getType().getName()+":"+target.getRunTarget().getId();
}
public void answerPasswordPrompt(CfUserInteractions ui, PasswordAnswerer answerer) {
doAnswer(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
PasswordDialogModel dialog = (PasswordDialogModel) invocation.getArguments()[0];
answerer.apply(dialog);
return dialog.isOk();
}
}).when(ui).openPasswordDialog(any(PasswordDialogModel.class));
}
public List<BootDashModel> getCfRunTargetModels() {
return getRunTargetModels(cfTargetType());
}
public CloudFoundryRunTargetType getCfTargetType() {
for (RunTargetType type : model.getRunTargetTypes()) {
if (type instanceof CloudFoundryRunTargetType) {
return (CloudFoundryRunTargetType) type;
}
}
return null;
}
/**
* Raw fetch of environment variables (makes a request through the CF client, rather then get the cached data
* from the model).
*/
public Map<String, String> fetchEnvironment(CloudFoundryBootDashModel model, String appName) throws Exception {
return model.getRunTarget().getClient().getApplication(appName).getEnvAsMap();
}
public LocalBootDashModel getLocalModel() {
return (LocalBootDashModel) getRunTargetModel(RunTargetTypes.LOCAL);
}
public void answerManifestDiffDialog(CfUserInteractions ui, Function<ManifestDiffDialogModel, ManifestDiffDialogModel.Result> answerer) throws Exception {
when(ui.openManifestDiffDialog(any()))
.thenAnswer(new Answer<ManifestDiffDialogModel.Result>() {
@Override
public ManifestDiffDialogModel.Result answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
ManifestDiffDialogModel dialog = (ManifestDiffDialogModel) args[0];
return answerer.apply(dialog);
}
});
}
public SecuredCredentialsStore getCredentialsStore() {
return context.getSecuredCredentialsStore();
}
public IPropertyStore getPrivateStore() {
return context.getPrivatePropertyStore();
}
public JmxSshTunnelManager getJmxSshTunnelManager() {
return context.injections.getBean(JmxSshTunnelManager.class);
}
}

View File

@@ -1,112 +0,0 @@
/*******************************************************************************
* Copyright (c) 2015 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test;
import java.io.File;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jdt.core.JavaCore;
import org.springframework.ide.eclipse.boot.dash.cf.packaging.JarNameGenerator;
import org.springframework.ide.eclipse.boot.util.JavaProjectUtil;
import org.springsource.ide.eclipse.commons.tests.util.StsTestCase;
public class JarNameGeneratorTest extends StsTestCase {
private JarNameGenerator ng = new JarNameGenerator();
public void testNamesForJars() {
assertName("foo-1.2.3.jar", "/home/someplace/foo-1.2.3.jar");
assertName("foo-1.2.3-1.jar", "/home/some-other-place/foo-1.2.3.jar");
assertName("foo-1.2.3-2.jar", "/home/and-yet-another/foo-1.2.3.jar");
//counters are per-name not per JarNameGenerator instance?
assertName("bar.jar", "/home/bar.jar");
assertName("bar-1.jar", "/away/bar.jar");
//Tolerate '.JAR' in upper case?
assertName("case-nutter.jar", "/somewhere/case-nutter.JAR");
assertName("case-nutter-1.jar", "/elsewhere/case-nutter.JAR");
}
public void testNamesForProjectFolders() throws Exception {
IProject p = createPredefinedProject("demo-lib");
IContainer _outputFolder = JavaProjectUtil.getDefaultOutputFolder(JavaCore.create(p));
File outputFolder = _outputFolder.getLocation().toFile();
assertName("demo-lib.jar", outputFolder);
assertName("demo-lib-1.jar", outputFolder);
assertName("demo-lib-2.jar", outputFolder);
}
public void testNamesForNestedProjectFolders() throws Exception {
IProject p = createPredefinedProject("demo-lib");
String nestedName = "nested";
IProject nested = createGeneralProject(p, nestedName, p.getLocation().append(nestedName));
File dep = nested.getLocation().toFile();
//The next bit is to check that this is actually a good test. I.e.
// We do in fact have a situation where a nested project implies that several resources in the
// workspace represent the same folder on disk.
IContainer[] containers = getWSRoot().findContainersForLocationURI(dep.toURI());
assertEquals(2, containers.length);
//Now check that it makes the right choice and names the jar after 'nested' not after 'demo-lib'.
assertName("nested.jar", dep);
assertName("nested-1.jar", dep);
assertName("nested-2.jar", dep);
}
protected IProject createGeneralProject(IProject p, String name, IPath loc) throws CoreException {
IProjectDescription desc = getWorkspace().newProjectDescription(name);
IProject nested = getProject(name);
desc.setLocation(loc);
nested.create(desc, new NullProgressMonitor());
return nested;
}
private IProject getProject(String name) {
return getWSRoot().getProject(name);
}
protected IWorkspaceRoot getWSRoot() {
return getWorkspace().getRoot();
}
protected IWorkspace getWorkspace() {
return ResourcesPlugin.getWorkspace();
}
private void assertName(String expectedName, File dep) {
assertEquals(expectedName, ng.createName(dep));
}
private void assertName(String expectedName, String depPath) {
assertName(expectedName, new File(depPath));
}
@Override
protected String getBundleName() {
return BootDashTestBundleConstants.BUNDLE_ID;
}
}

View File

@@ -1,107 +0,0 @@
/*******************************************************************************
* Copyright (c) 2018 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.springframework.ide.eclipse.boot.dash.cf.debug.SshTunnelFactory;
import org.springframework.ide.eclipse.boot.dash.cf.jmxtunnel.JmxSshTunnelManager;
import org.springframework.ide.eclipse.boot.dash.cf.jmxtunnel.JmxSupport;
import org.springframework.ide.eclipse.boot.dash.cf.model.CloudAppDashElement;
import org.springframework.ide.eclipse.boot.dash.model.RunState;
import org.springframework.ide.eclipse.boot.dash.test.mocks.MockSshTunnel;
import org.springsource.ide.eclipse.commons.livexp.core.LiveExpression;
public class JmxSupportTest {
CloudAppDashElement cde = mock(CloudAppDashElement.class);
JmxSshTunnelManager tunnels = new JmxSshTunnelManager();
SshTunnelFactory tunnelFactory = MockSshTunnel::new;
@Test
public void setupEnvVars() throws Exception {
int testPort = 1234;
when(cde.getBaseRunStateExp()).thenReturn(LiveExpression.constant(RunState.INACTIVE));
JmxSupport jmx = new JmxSupport(cde, tunnels, tunnelFactory) {
public int getPort() {return testPort; }
};
Map<String, String> env = new HashMap<>();
jmx.setupEnvVars(env);
assertEquals(
"-Dcom.sun.management.jmxremote.ssl=false "
+ "-Dcom.sun.management.jmxremote.authenticate=false "
+ "-Dcom.sun.management.jmxremote.port=1234 "
+ "-Dcom.sun.management.jmxremote.rmi.port=1234 "
+ "-Djava.rmi.server.hostname=localhost "
+ "-Dcom.sun.management.jmxremote.local.only=false "
+ "-Dspring.jmx.enabled=true"
+ "-Dmanagement.endpoints.jmx.exposure.include=*",
env.get("JAVA_OPTS"));
jmx.setupEnvVars(env); // should erase old and recreate
assertEquals(
"-Dcom.sun.management.jmxremote.ssl=false "
+ "-Dcom.sun.management.jmxremote.authenticate=false "
+ "-Dcom.sun.management.jmxremote.port=1234 "
+ "-Dcom.sun.management.jmxremote.rmi.port=1234 "
+ "-Djava.rmi.server.hostname=localhost "
+ "-Dcom.sun.management.jmxremote.local.only=false "
+ "-Dspring.jmx.enabled=true"
+ "-Dmanagement.endpoints.jmx.exposure.include=*",
env.get("JAVA_OPTS"));
}
@Test
public void setupEnvVars_preserve_unrelated_java_opts() throws Exception {
int testPort = 1234;
when(cde.getBaseRunStateExp()).thenReturn(LiveExpression.constant(RunState.INACTIVE));
JmxSupport jmx = new JmxSupport(cde, tunnels, tunnelFactory) {
public int getPort() {return testPort; }
};
Map<String, String> env = new HashMap<>();
env.put("JAVA_OPTS", "-Dsomething.already=here");
jmx.setupEnvVars(env);
assertEquals("-Dsomething.already=here "
+ "-Dcom.sun.management.jmxremote.ssl=false "
+ "-Dcom.sun.management.jmxremote.authenticate=false "
+ "-Dcom.sun.management.jmxremote.port=1234 "
+ "-Dcom.sun.management.jmxremote.rmi.port=1234 "
+ "-Djava.rmi.server.hostname=localhost "
+ "-Dcom.sun.management.jmxremote.local.only=false "
+ "-Dspring.jmx.enabled=true"
+ "-Dmanagement.endpoints.jmx.exposure.include=*",
env.get("JAVA_OPTS"));
jmx.setupEnvVars(env); // should erase old and recreate
assertEquals("-Dsomething.already=here "
+ "-Dcom.sun.management.jmxremote.ssl=false "
+ "-Dcom.sun.management.jmxremote.authenticate=false "
+ "-Dcom.sun.management.jmxremote.port=1234 "
+ "-Dcom.sun.management.jmxremote.rmi.port=1234 "
+ "-Djava.rmi.server.hostname=localhost "
+ "-Dcom.sun.management.jmxremote.local.only=false "
+ "-Dspring.jmx.enabled=true"
+ "-Dmanagement.endpoints.jmx.exposure.include=*",
env.get("JAVA_OPTS"));
}
}

View File

@@ -1,312 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 Spring IDE Developers
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Spring IDE Developers - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test;
import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.stream.Collectors;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.junit.Test;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFCloudDomain;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFDomainType;
import org.springframework.ide.eclipse.boot.dash.cf.client.v2.CFCloudDomainData;
import org.springframework.ide.eclipse.boot.dash.cf.client.v2.CFDomainStatus;
import org.springframework.ide.eclipse.boot.dash.cf.deployment.CloudData;
import org.springframework.ide.eclipse.boot.dash.cf.deployment.YamlGraphDeploymentProperties;
import org.springframework.ide.eclipse.boot.dash.cf.routes.RouteAttributes;
import org.springframework.ide.eclipse.boot.dash.cf.routes.RouteBinding;
import org.springframework.ide.eclipse.boot.dash.cf.routes.RouteBuilder;
import org.springframework.ide.eclipse.editor.support.yaml.ast.NodeUtil;
import org.springframework.ide.eclipse.editor.support.yaml.ast.YamlASTProvider;
import org.springframework.ide.eclipse.editor.support.yaml.ast.YamlFileAST;
import org.springframework.ide.eclipse.editor.support.yaml.path.YamlPath;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.nodes.Node;
import com.google.common.collect.ImmutableList;
public class RouteBuilderTest {
List<CFCloudDomain> TEST_DOMAINS = ImmutableList.of(
new CFCloudDomainData("tcp.cfapps.io", CFDomainType.TCP, CFDomainStatus.SHARED),
new CFCloudDomainData("testing.me", CFDomainType.HTTP, CFDomainStatus.OWNED),
new CFCloudDomainData("cfapps.io")
);
@Test
public void appNameOnly() throws Exception {
assertRoutes(
"applications:\n" +
"- name: my-app\n"
, //=>
"my-app@cfapps.io"
);
}
@Test
public void domainAndHost() throws Exception {
assertRoutes(
"applications:\n" +
"- name: my-app\n" +
" domain: testing.me\n" +
" host: some-host"
, //=>
"some-host@testing.me"
);
}
@Test
public void domainOnly() throws Exception {
assertRoutes(
"applications:\n" +
"- name: my-app\n" +
" domain: testing.me\n"
, //=>
"my-app@testing.me"
);
}
@Test
public void domainAndNoHost() throws Exception {
assertRoutes(
"applications:\n" +
"- name: my-app\n" +
" domain: testing.me\n" +
" no-hostname: true"
, //=>
"testing.me"
);
}
@Test
public void noHostOnly() throws Exception {
assertRoutes(
"applications:\n" +
"- name: my-app\n" +
" no-hostname: true"
, //=>
"cfapps.io"
);
}
@Test public void noRoute() throws Exception {
assertRoutes(
"applications:\n" +
"- name: foo\n" +
" no-route: true"
// ==>
/* NONE */
);
}
@Test
public void multipleDomainsAndHosts() throws Exception {
assertRoutes(
"applications:\n" +
"- name: my-app\n" +
" domains: [testing.me, cfapps.io]\n" +
" hosts: [foo, bar]\n"
, // ==>
"foo@testing.me",
"foo@cfapps.io",
"bar@testing.me",
"bar@cfapps.io"
);
}
@Test
public void randomRouteNoDomain() throws Exception {
assertRoutes(
"applications:\n" +
"- name: my-app\n" +
" random-route: true\n"
,
"?@cfapps.io"
);
}
@Test
public void randomRouteHttpDomain() throws Exception {
assertRoutes(
"applications:\n" +
"- name: my-app\n" +
" random-route: true\n" +
" domain: testing.me\n"
,
"?@testing.me"
);
}
@Test
public void randomRouteTcpDomain() throws Exception {
assertRoutes(
"applications:\n" +
"- name: my-app\n" +
" random-route: true\n" +
" domain: tcp.cfapps.io\n"
,
"tcp.cfapps.io:?"
);
}
@Test
public void variousUriRoutes() throws Exception {
assertRoutes(
"applications:\n" +
"- name: my-app\n" +
" routes:\n" +
" - route: foo.cfapps.io/somepath\n" +
" - route: cfapps.io\n" +
" - route: tcp.cfapps.io:63111\n" +
" - route: bar.testing.me\n" +
" - route: ambiguous.tcp.cfapps.io\n"
, // =>
"foo@cfapps.io/somepath",
"cfapps.io",
"tcp.cfapps.io:63111",
"bar@testing.me",
"ambiguous@tcp.cfapps.io"
);
}
@Test
public void noCuttingInTheMiddleOfAWord() throws Exception {
{
List<CFCloudDomain> domains = ImmutableList.of(
new CFCloudDomainData("irrellevant.com"),
new CFCloudDomainData("thing.com"),
new CFCloudDomainData("something.com")
);
assertRoutes(domains,
"applications:\n" +
"- name: my-app\n" +
" routes:\n" +
" - route: foo.something.com\n"
, // ==>
"foo@something.com"
);
}
{
List<CFCloudDomain> domains = ImmutableList.of(
new CFCloudDomainData("irrellevant.com"),
new CFCloudDomainData("thing.com"),
new CFCloudDomainData("com")
);
assertRoutes(domains,
"applications:\n" +
"- name: my-app\n" +
" routes:\n" +
" - route: foo.something.com\n"
, // ==>
"foo.something@com"
);
}
}
/////// Some edge cases below. Their behavior isn't really that important, but the tests
// just here to formally cover the corresponding branches in the code, and make sure
// they don't behave irrationally or crash. These tests are probably 'over-specified' in
// that they test behaviors client code shouldn't have to / want to care about.
@Test
public void noKnownDomains() throws Exception {
assertRoutes(ImmutableList.of(),
"applications:\n" +
"- name: my-app\n" +
" routes:\n" +
" - route: some.thing.com\n"
// =>
/* NONE */
);
assertRoutes(ImmutableList.of(),
"applications:\n" +
"- name: my-app\n"
// =>
/* NONE */
);
}
@Test
public void bogusDomain() throws Exception {
assertRoutes(ImmutableList.of(),
"applications:\n" +
"- name: my-app\n" +
" random-route: true\n" +
" domain: bogus.com\n" +
" domains: [ bogus.me, cfapps.io]\n"
, // =>
//Rationale for the below results. When determining random-route behavior
// for unknown domain assume its http, i.e. the most common case.
"?@bogus.me" ,
"?@cfapps.io",
"?@bogus.com"
);
}
////////////////////////////////////////////////////////////////////////////////////
private void assertRoutes(String manifestText, String... expectedRoutes) {
assertRoutes(TEST_DOMAINS, manifestText, expectedRoutes);
}
private void assertRoutes(List<CFCloudDomain> domains, String manifestText, String... expectedRoutes) {
//Why the loop? This improves test coverage. The test should pass the same repeatedly, its behavior
// should not change. It *might* change if we have some kind of bug where cached state influences the
// behavior inadvertently in a manner visible to a caller.
for (int i = 0; i < 3; i++) {
RouteBuilder rb = new RouteBuilder(domains);
List<RouteBinding> routes = rb.buildRoutes(parse(domains,
manifestText));
StringBuilder expected = new StringBuilder();
StringBuilder expectedUri = new StringBuilder();
for (String r : expectedRoutes) {
expected.append(r+"\n");
expectedUri.append(r.replace("@", "."));
}
StringBuilder actual = new StringBuilder();
StringBuilder actualUri = new StringBuilder();
for (RouteBinding r : routes) {
actual.append(r+"\n");
actualUri.append(r.toUri());
}
assertEquals(expected.toString(), actual.toString());
assertEquals(expectedUri.toString(), actualUri.toString());
}
}
/**
* Parse a manifest with a single
* @param manifestText
* @return
*/
private RouteAttributes parse(List<CFCloudDomain> domains, String manifestText) {
IDocument doc = new Document(manifestText);
YamlASTProvider parser = new YamlASTProvider(new Yaml(new SafeConstructor()));
YamlFileAST ast = parser.getAST(doc);
List<Node> names = YamlPath.EMPTY
.thenAnyChild()
.thenValAt("applications")
.thenAnyChild()
.thenValAt("name")
.traverseAmbiguously(ast)
.collect(Collectors.toList());
assertEquals("Number of apps in manifest", 1, names.size());
String appName = NodeUtil.asScalar(names.get(0));
CloudData cloudData = new CloudData(domains, "some-buildpack", ImmutableList.of());
YamlGraphDeploymentProperties dp = new YamlGraphDeploymentProperties(manifestText, appName, cloudData);
return new RouteAttributes(dp);
}
}

View File

@@ -25,12 +25,6 @@ import org.eclipse.debug.core.ILaunchManager;
import org.springframework.ide.eclipse.boot.core.BootPreferences;
import org.springframework.ide.eclipse.boot.core.cli.BootInstallManager;
import org.springframework.ide.eclipse.boot.dash.api.RunTargetType;
import org.springframework.ide.eclipse.boot.dash.cf.actions.CfBootDashActions;
import org.springframework.ide.eclipse.boot.dash.cf.client.CloudFoundryClientFactory;
import org.springframework.ide.eclipse.boot.dash.cf.debug.DebugSupport;
import org.springframework.ide.eclipse.boot.dash.cf.debug.SshDebugSupport;
import org.springframework.ide.eclipse.boot.dash.cf.debug.SshTunnelFactory;
import org.springframework.ide.eclipse.boot.dash.cf.jmxtunnel.JmxSshTunnelManager;
import org.springframework.ide.eclipse.boot.dash.console.CloudAppLogManager;
import org.springframework.ide.eclipse.boot.dash.di.SimpleDIContext;
import org.springframework.ide.eclipse.boot.dash.model.BootDashModelContext;
@@ -39,9 +33,6 @@ import org.springframework.ide.eclipse.boot.dash.model.SecuredCredentialsStore;
import org.springframework.ide.eclipse.boot.dash.model.remote.GenericRemoteAppElementDataContributor;
import org.springframework.ide.eclipse.boot.dash.test.mocks.MockScopedPropertyStore;
import org.springframework.ide.eclipse.boot.dash.test.mocks.MockSecuredCredentialStore;
import org.springframework.ide.eclipse.boot.dash.test.mocks.MockSshTunnel;
import org.springframework.ide.eclipse.boot.dash.views.BootDashActions;
import org.springsource.ide.eclipse.commons.boot.ls.remoteapps.RemoteBootAppsDataHolder.Contributor;
import org.springsource.ide.eclipse.commons.core.pstore.IPropertyStore;
import org.springsource.ide.eclipse.commons.core.pstore.IScopedPropertyStore;
import org.springsource.ide.eclipse.commons.core.pstore.InMemoryPropertyStore;
@@ -83,11 +74,7 @@ public class TestBootDashModelContext extends BootDashModelContext {
private static SimpleDIContext createInjections() {
SimpleDIContext injections = new SimpleDIContext();
injections.defInstance(AllUserInteractions.class, mock(AllUserInteractions.class));
injections.defInstance(BootDashActions.Factory.class, CfBootDashActions.factory);
injections.defInstance(DebugSupport.class, SshDebugSupport.INSTANCE);
injections.def(BootDashViewModel.class, BootDashViewModel::new);
injections.defInstance(SshTunnelFactory.class, MockSshTunnel::new);
injections.defInstance(JmxSshTunnelManager.class, new JmxSshTunnelManager());
injections.def(CloudAppLogManager.class, CloudAppLogManager::new); //TODO: replace with a mock?
injections.def(GenericRemoteAppElementDataContributor.class, GenericRemoteAppElementDataContributor::new);
return injections;
@@ -167,11 +154,6 @@ public class TestBootDashModelContext extends BootDashModelContext {
return this;
}
public TestBootDashModelContext withCfClient(CloudFoundryClientFactory client) {
injections.defInstance(CloudFoundryClientFactory.class, client);
return this;
}
public RunTargetType getRargetTypeWithName(String name) {
return injections.getBeans(RunTargetType.class).stream().filter(t -> t.getName().equals(name)).findFirst().orElse(null);
}

View File

@@ -1,43 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test.mocks;
import java.util.UUID;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFOrganization;
/**
* Data object implementing {@link CFOrganization}
*
* @author Kris De Volder
*/
public class CFOrganizationData implements CFOrganization {
private String name;
private UUID guid;
public CFOrganizationData(String name, UUID guid) {
super();
this.name = name;
this.guid = guid;
}
@Override
public String getName() {
return name;
}
@Override
public UUID getGuid() {
return guid;
}
}

View File

@@ -1,58 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test.mocks;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFServiceInstance;
public class CFServiceInstanceData implements CFServiceInstance {
private String name;
public CFServiceInstanceData(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public String getPlan() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getDashboardUrl() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getService() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getDocumentationUrl() {
// TODO Auto-generated method stub
return null;
}
}

View File

@@ -1,49 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test.mocks;
import java.util.UUID;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFOrganization;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFSpace;
/**
* @author Kris De Volder
*/
public class CFSpaceData implements CFSpace {
private String name;
private UUID guid;
private CFOrganization org;
public CFSpaceData(String name, UUID guid, CFOrganization org) {
super();
this.name = name;
this.guid = guid;
this.org = org;
}
@Override
public String getName() {
return name;
}
@Override
public CFOrganization getOrganization() {
return org;
}
@Override
public UUID getGuid() {
return guid;
}
}

View File

@@ -1,434 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test.mocks;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.eclipse.core.runtime.Assert;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFAppState;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFApplication;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFApplicationDetail;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFInstanceState;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFInstanceStats;
import org.springframework.ide.eclipse.boot.dash.cf.client.InstanceState;
import org.springframework.ide.eclipse.boot.dash.cf.client.v2.ApplicationExtras;
import org.springframework.ide.eclipse.boot.dash.cf.client.v2.CFApplicationDetailData;
import org.springframework.ide.eclipse.boot.dash.cf.client.v2.CFApplicationSummaryData;
import org.springframework.ide.eclipse.boot.dash.cf.routes.RouteBinding;
import org.springframework.ide.eclipse.boot.dash.cloudfoundry.deployment.DeploymentProperties;
import org.springframework.ide.eclipse.boot.dash.util.CancelationTokens;
import org.springframework.ide.eclipse.boot.dash.util.CancelationTokens.CancelationToken;
import org.springsource.ide.eclipse.commons.frameworks.test.util.ACondition;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.google.common.collect.ImmutableMap;
import reactor.core.publisher.Mono;
public class MockCFApplication {
private static class MockCFInstanceStats implements CFInstanceStats {
private CFInstanceState state;
public MockCFInstanceStats(CFInstanceState state) {
this.state = state;
}
@Override
public CFInstanceState getState() {
return state;
}
@Override
public String toString() {
return "CFInstanceState("+state+")";
}
}
private final String name;
private final UUID guid;
private int instances;
private Map<String, String> env = new HashMap<>();
private int memory = 1024;
private List<String> services = new ArrayList<>();
private String buildpackUrl = null;
private List<RouteBinding> routes = new ArrayList<>();
private CFAppState state = CFAppState.STOPPED;
private int diskQuota = 1024;
private Integer timeout = null;
private String healthCheckType = DeploymentProperties.DEFAULT_HEALTH_CHECK_TYPE;
private String healthCheckHttpEndpoint = null;
private String command = null;
private String stack = null;
private MockCloudFoundryClientFactory owner;
private MockCFSpace space;
public MockCFApplication(MockCloudFoundryClientFactory owner, MockCFSpace space, String name, UUID guid, int instances, CFAppState state) {
this.owner = owner;
this.space = space;
this.name = name;
this.guid = guid;
this.instances = instances;
this.state = state;
this.cancelationTokens = new CancelationTokens();
}
private ImmutableList<CFInstanceStats> stats = ImmutableList.of();
private CancelationTokens cancelationTokens;
private Supplier<byte[]> bits;
public MockCFApplication(MockCloudFoundryClientFactory owner, MockCFSpace space, String name) {
this(owner,
space,
name,
UUID.randomUUID(),
1,
CFAppState.STOPPED
);
}
public String getName() {
return name;
}
public List<CFInstanceStats> getStats() {
return stats;
}
public void start(CancelationToken cancelationToken) throws Exception {
Assert.isLegal(CFAppState.STOPPED==state);
Assert.isLegal(stats.isEmpty());
this.state = CFAppState.UNKNOWN;
final long endTime = System.currentTimeMillis()+getStartDelay();
new ACondition("simulated app starting (waiting)", getStartDelay()+1000) {
@Override
public boolean test() throws Exception {
// System.out.println("Checking token: "+cancelToken);
if (!cancelationToken.isCanceled() && System.currentTimeMillis()<endTime) {
System.out.println("Starting "+getName()+"...");
throw new IOException("App still starting");
}
return true;
}
};
Builder<CFInstanceStats> builder = ImmutableList.builder();
for (int i = 0; i < instances; i++) {
Map<String, Object> values = new HashMap<>();
values.put("state", InstanceState.RUNNING.toString());
CFInstanceStats stat = new MockCFInstanceStats(CFInstanceState.RUNNING);
builder.add(stat);
}
if (cancelationToken.isCanceled()) {
System.out.println("Starting "+getName()+" CANCELED");
throw new IOException("Operation Canceled");
}
this.stats = builder.build();
this.state = CFAppState.STARTED;
System.out.println("Starting "+getName()+" SUCCESS");
}
private long getStartDelay() {
return owner.getStartDelay();
}
public String getHealthCheckType() {
return healthCheckType;
}
public void setHealthCheckType(String t) {
this.healthCheckType = t;
}
public String getHealthCheckHttpEndpoint() {
return healthCheckHttpEndpoint;
}
public void setHealthCheckHttpEndpoint(String t) {
this.healthCheckHttpEndpoint = t;
}
public void setHealthCheckTypeMaybe(String t) {
if (t!=null) {
setHealthCheckType(t);
}
}
// public int getInstances() {
// return instances;
// }
public int getRunningInstances() {
int runningInstances = 0;
for (CFInstanceStats instance : getStats()) {
if (instance.getState()==CFInstanceState.RUNNING) {
runningInstances++;
}
}
return runningInstances;
}
public UUID getGuid() {
return guid;
}
public void setBuildpackUrl(String buildpackUrl) {
this.buildpackUrl = buildpackUrl;
}
public void setCommand(String command) {
this.command = command;
}
public void setStack(String stack) {
this.stack = stack;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public void setDiskQuota(int diskQuota) {
this.diskQuota = diskQuota;
}
public void setMemory(int memory) {
this.memory = memory;
}
public int getMemory() {
return this.memory;
}
public void setRoutes(Collection<RouteBinding> routes) {
this.routes = routes==null?null:ImmutableList.copyOf(routes);
}
public void setServices(Collection<String> services) {
this.services = services==null?null:ImmutableList.copyOf(services);
}
public CFApplication getBasicInfo() {
return new CFApplicationSummaryData(
name,
instances,
getRunningInstances(),
memory,
guid,
getUris(),
state,
diskQuota,
getExtras()
);
}
private List<String> getUris() {
return routes.stream()
.map(RouteBinding::toUri)
.collect(Collectors.toList());
}
private ApplicationExtras getExtras() {
return new ApplicationExtras() {
@Override
public Mono<String> getStack() {
return Mono.justOrEmpty(stack);
}
@Override
public Mono<List<String>> getServices() {
return Mono.justOrEmpty(services);
}
@Override
public Mono<Map<String, String>> getEnv() {
return Mono.justOrEmpty(env);
}
@Override
public Mono<String> getBuildpack() {
return Mono.justOrEmpty(buildpackUrl);
}
@Override
public Mono<Integer> getTimeout() {
return Mono.justOrEmpty(timeout);
}
@Override
public Mono<String> getCommand() {
return Mono.justOrEmpty(command);
}
@Override
public Mono<String> getHealthCheckType() {
return Mono.justOrEmpty(healthCheckType);
}
@Override
public Mono<String> getHealthCheckHttpEndpoint() {
return Mono.justOrEmpty(healthCheckHttpEndpoint);
}
};
}
public CFApplicationDetail getDetailedInfo() {
return new CFApplicationDetailData(
new CFApplicationSummaryData(
name,
instances,
getRunningInstances(),
memory,
guid,
getUris(),
state,
diskQuota,
getExtras()
),
ImmutableList.copyOf(stats)
);
// return new CFApplicationDetailData(getBasicInfo(), ImmutableList.copyOf(stats));
}
@Override
public String toString() {
return "MockCFApp("+name+")";
}
public void stop() {
cancelationTokens.cancelAll();
this.stats = ImmutableList.of();
this.state = CFAppState.STOPPED;
}
public Map<String, String> getEnv() {
return env;
}
public void setEnv(Map<String, String> newEnv) {
env = ImmutableMap.copyOf(newEnv);
}
public void restart(CancelationToken cancelationToken) throws Exception {
stop();
start(cancelationToken);
}
public void scaleInstances(int desiredInstances) {
Assert.isLegal(desiredInstances>0);
Builder<CFInstanceStats> builder = ImmutableList.builder();
builder.addAll(stats);
for (int i = 0; i < desiredInstances; i++) {
builder.add(new MockCFInstanceStats(CFInstanceState.RUNNING));
}
stats = builder.build();
this.instances = desiredInstances;
}
public void setBuildpackUrlMaybe(String buildpack) {
if (buildpack!=null) {
setBuildpackUrl(buildpack);
}
}
public void setCommandMaybe(String command) {
if (command!=null) {
setCommand(command);
}
}
public void setDiskQuotaMaybe(Integer diskQuota) {
if (diskQuota!=null) {
setDiskQuota(diskQuota);
}
}
public void setEnvMaybe(Map<String, String> env) {
if (env!=null) {
setEnv(env);
}
}
public void setMemoryMaybe(Integer memory) {
if (memory!=null) {
setMemory(memory);
}
}
public void setServicesMaybe(List<String> services) {
if (services!=null) {
setServices(services);
}
}
public void setStackMaybe(String stack) {
if (stack!=null) {
setStack(stack);
}
}
public void setTimeoutMaybe(Integer timeout) {
if (timeout!=null) {
setTimeout(timeout);
}
}
public int getPushCount() {
return space.getPushCount(name).getValue();
}
public String getFileContents(String path) throws IOException {
ZipInputStream zip = new ZipInputStream(getBits());
ZipEntry entry;
while (null != (entry = zip.getNextEntry())) {
if (!entry.isDirectory()) {
if (entry.getName().equals(path)) {
return new String(readBytes(zip));
}
}
}
return null;
}
private byte[] readBytes(ZipInputStream zip) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
int nextByte;
while ((nextByte = zip.read())>=0) {
bytes.write(nextByte);
}
return bytes.toByteArray();
}
public void setBits(Supplier<byte[]> bytes) {
this.bits = bytes;
}
public ByteArrayInputStream getBits() {
return new ByteArrayInputStream(bits.get());
}
}

View File

@@ -1,28 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test.mocks;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFBuildpack;
public class MockCFBuildpack implements CFBuildpack{
private String name;
public MockCFBuildpack(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
}

View File

@@ -1,122 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test.mocks;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.mockito.Mockito;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFApplication;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFOrganization;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFServiceInstance;
import org.springsource.ide.eclipse.commons.livexp.core.LiveCounter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
public class MockCFSpace extends CFSpaceData {
//TODO: the methods in this class should prolly be synchronized somehow. It manipulates mutable
// data and is called from multiple threads.
private Map<String, CFServiceInstance> servicesByName = new HashMap<>();
private Map<String, MockCFApplication> appsByName = new HashMap<>();
private MockCloudFoundryClientFactory owner;
private Map<String, LiveCounter> pushCounts = new HashMap<>();
public MockCFSpace(MockCloudFoundryClientFactory owner, String name, UUID guid, CFOrganization org) {
super(name, guid, org);
this.owner = owner;
}
public String getDefaultDomain() {
return owner.getDefaultDomain();
}
public List<CFServiceInstance> getServices() {
return ImmutableList.copyOf(servicesByName.values());
}
public ImmutableList<CFApplication> getApplicationsWithBasicInfo() {
Builder<CFApplication> builder = ImmutableList.builder();
for (MockCFApplication app : appsByName.values()) {
builder.add(app.getBasicInfo());
}
return builder.build();
}
public MockCFApplication defApp(String name) {
MockCFApplication existing = appsByName.get(name);
if (existing==null) {
appsByName.put(name, existing = Mockito.spy(new MockCFApplication(owner, this, name)));
}
return existing;
}
public CFServiceInstance defService(String name) {
CFServiceInstance existing = servicesByName.get(name);
if (existing==null) {
servicesByName.put(name, new CFServiceInstanceData(
name
));
}
return existing;
}
public MockCFApplication getApplication(UUID appGuid) {
for (MockCFApplication app : appsByName.values()) {
if (app.getGuid().equals(appGuid)) {
return app;
}
}
return null;
}
public MockCFApplication getApplication(String appName) {
MockCFApplication app = appsByName.get(appName);
if (app!=null) {
return app;
}
return null;
}
public boolean removeApp(String name) {
return appsByName.remove(name)!=null;
}
public void put(MockCFApplication app) {
appsByName.put(app.getName(), app);
}
public synchronized LiveCounter getPushCount(String name) {
LiveCounter counter = pushCounts.get(name);
if (counter==null) {
pushCounts.put(name, counter = new LiveCounter());
}
return counter;
}
public void deleteService(String serviceName) throws Exception {
CFServiceInstance x = servicesByName.remove(serviceName);
if (x==null) {
throw new IOException("Service doesn't exist: "+serviceName);
}
}
@Override
public String toString() {
return "MockCFSpace("+getName()+")";
}
}

View File

@@ -1,32 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test.mocks;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFStack;
/**
* @author Kris De Volder
*/
public class MockCFStack implements CFStack {
private String name;
public MockCFStack(String name) {
super();
this.name = name;
}
@Override
public String getName() {
return name;
}
}

View File

@@ -1,667 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test.mocks;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.commons.lang.RandomStringUtils;
import org.cloudfoundry.client.CloudFoundryClient;
import org.osgi.framework.Version;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFApplication;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFApplicationDetail;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFBuildpack;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFClientParams;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFCloudDomain;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFCredentials;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFDomainType;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFOrganization;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFServiceInstance;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFSpace;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFStack;
import org.springframework.ide.eclipse.boot.dash.cf.client.ClientRequests;
import org.springframework.ide.eclipse.boot.dash.cf.client.CloudFoundryClientFactory;
import org.springframework.ide.eclipse.boot.dash.cf.client.SshClientSupport;
import org.springframework.ide.eclipse.boot.dash.cf.client.SshHost;
import org.springframework.ide.eclipse.boot.dash.cf.client.CFCredentials.CFCredentialType;
import org.springframework.ide.eclipse.boot.dash.cf.client.v2.CFCloudDomainData;
import org.springframework.ide.eclipse.boot.dash.cf.client.v2.CFDomainStatus;
import org.springframework.ide.eclipse.boot.dash.cf.client.v2.CFPushArguments;
import org.springframework.ide.eclipse.boot.dash.cf.routes.ParsedUri;
import org.springframework.ide.eclipse.boot.dash.cf.routes.RouteBinding;
import org.springframework.ide.eclipse.boot.dash.console.IApplicationLogConsole;
import org.springframework.ide.eclipse.boot.dash.test.CfTestTargetParams;
import org.springframework.ide.eclipse.boot.dash.test.util.LiveExpToFlux;
import org.springframework.ide.eclipse.boot.dash.util.CancelationTokens.CancelationToken;
import org.springsource.ide.eclipse.commons.livexp.core.LiveVariable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import junit.framework.Assert;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class MockCloudFoundryClientFactory extends CloudFoundryClientFactory {
private static void debug(String string) {
System.out.println(string);
}
private final Set<MockClient> instances = Collections.synchronizedSet(new HashSet<>());
public static final String FAKE_REFRESH_TOKEN = "fakeRefreshToken";
public static final String FAKE_PASSWORD = CfTestTargetParams.fromEnv("CF_TEST_PASSWORD");
private Version supportedApiVersion = new Version(CloudFoundryClient.SUPPORTED_API_VERSION);
private Version apiVersion = supportedApiVersion;
private Map<String, CFOrganization> orgsByName = new LinkedHashMap<>();
private Map<String, MockCFSpace> spacesByName = new LinkedHashMap<>();
private Map<String, CFCloudDomainData> domainsByName = new LinkedHashMap<>();
private Map<String, MockCFBuildpack> buildpacksByName = new LinkedHashMap<>();
private Map<String, MockCFStack> stacksByName = new LinkedHashMap<>();
private Set<String> ssoTokens = new HashSet<>();
/**
* Becomes non-null if notImplementedStub is called, used to check that the tests
* only use parts of the mocking harness that are actually implemented.
*/
private Exception notImplementedStubCalled = null;
private long startDelay = 0;
public MockCloudFoundryClientFactory() {
defDomain("cfmockapps.io"); //Lost of functionality may assume there's at least one domain so make sure we have one.
defBuildpacks("java-buildpack", "ruby-buildpack", "funky-buildpack", "another-buildpack");
defStacks("cflinuxfs2", "windows2012R2");
}
synchronized public String getSsoToken() {
String token = RandomStringUtils.randomAlphabetic(8);
ssoTokens.add(token);
return token;
}
/**
* Verfies the validity of a sso token. Sso token can only be used once
* so this check implicitly invalidates the token.
*
* @return Whether the token was valid prior to the call to this method.
*/
private synchronized boolean checkSsoToken(String token) {
return ssoTokens.remove(token);
}
public void defStacks(String... names) {
for (String n : names) {
defStack(n);
}
}
public MockCFStack defStack(String name) {
MockCFStack stack = new MockCFStack(name);
stacksByName.put(name, stack);
return stack;
}
@Override
public ClientRequests getClient(CFClientParams params) {
return new MockClient(params);
}
public CFCloudDomain defDomain(String name) {
CFCloudDomainData it = new CFCloudDomainData(name);
domainsByName.put(name, it);
return it;
}
public CFCloudDomain defDomain(String name, CFDomainType type, CFDomainStatus status) {
CFCloudDomainData it = new CFCloudDomainData(name, type, status);
domainsByName.put(name, it);
return it;
}
public String getDefaultDomain() {
return domainsByName.keySet().iterator().next();
}
public MockCFSpace defSpace(String orgName, String spaceName) {
String key = orgName+"/"+spaceName;
MockCFSpace existing = spacesByName.get(key);
if (existing==null) {
CFOrganization org = defOrg(orgName);
spacesByName.put(key, existing= new MockCFSpace(this,
spaceName,
UUID.randomUUID(),
org
));
}
return existing;
}
public CFOrganization defOrg(String orgName) {
CFOrganization existing = orgsByName.get(orgName);
if (existing==null) {
orgsByName.put(orgName, existing = new CFOrganizationData(
orgName,
UUID.randomUUID()
));
}
return existing;
}
public void assertOnlyImplementedStubsCalled() throws Exception {
if (notImplementedStubCalled!=null) {
throw notImplementedStubCalled;
}
}
private String validPassword = FAKE_PASSWORD;
/**
* Change the current password this mock client will accept when trying to
* use password-based authentication.
*/
public void setPassword(String newPassword) {
this.validPassword = newPassword;
}
private class MockClient implements ClientRequests {
private class MockSshClientSupport implements SshClientSupport {
@Override
public SshHost getSshHost() throws Exception {
return new SshHost("ssh.host.somewhere", 2222, "some-ssh-fingerprint");
}
@Override
public String getSshUser(String appName, int instance) throws Exception {
MockCFApplication app = getSpace().getApplication(appName);
if (app==null) {
throw new IOException("App not found");
}
UUID guid = app.getGuid();
Assert.assertNotNull(guid);
return getSshUser(guid, instance);
}
@Override
public String getSshCode() throws Exception {
return "an-ssh-code";
}
@Override
public String getSshUser(UUID appGuid, int instance) throws Exception {
return appGuid+"/"+instance;
}
}
private int nextPort = 63000;
private synchronized int choosePort() {
return nextPort++;
}
private CFClientParams params;
private boolean connected = true;
private Boolean validCredentials = null;
private final LiveVariable<String> refreshToken = new LiveVariable<>();
public MockClient(CFClientParams params) {
this.params = params;
instances.add(this);
debug("created Mock CF Client: "+instances.size());
refreshToken.addListener((e,v) -> debug("refreshToken <- "+v));
refreshToken.onDispose(d -> debug("refreshToken DISPOSED"));
}
private void notImplementedStub() {
IllegalStateException e = new IllegalStateException("CF Client Stub Not Yet Implemented");
if (notImplementedStubCalled==null) {
notImplementedStubCalled = e;
}
throw e;
}
@Override
public Flux<CFApplicationDetail> getApplicationDetails(List<CFApplication> appsToLookUp) throws Exception {
checkConnection();
MockCFSpace space = getSpace();
return Flux.fromIterable(appsToLookUp)
.flatMap((app) -> {
return Mono.justOrEmpty(space.getApplication(app.getGuid()).getDetailedInfo());
});
}
@Override
public Disposable streamLogs(String appName, IApplicationLogConsole logConsole) throws Exception {
checkConnection();
//TODO: This 'log streamer' is a total dummy for now. It doesn't stream any data and canceling it does nothing.
return Flux.empty().subscribe();
}
@Override
public void stopApplication(String appName) throws Exception {
checkConnection();
MockCFApplication app = getSpace().getApplication(appName);
if (app==null) {
throw errorAppNotFound(appName);
}
app.stop();
}
@Override
public void restartApplication(String appName, CancelationToken cancelationToken) throws Exception {
checkConnection();
MockCFApplication app = getSpace().getApplication(appName);
if (app==null) {
throw errorAppNotFound(appName);
}
app.restart(cancelationToken);
}
@Override
public void dispose() {
connected = false;
refreshToken.dispose();
instances.remove(this);
debug("Mock CF Client disposed: "+instances.size());
}
@Override
public SshClientSupport getSshClientSupport() throws Exception {
return new MockSshClientSupport();
}
@SuppressWarnings("unchecked")
@Override
public List<CFSpace> getSpaces() throws Exception {
checkConnection();
@SuppressWarnings("rawtypes")
List hack = ImmutableList.copyOf(spacesByName.values());
return hack;
}
@Override
public List<CFServiceInstance> getServices() throws Exception {
checkConnection();
return getSpace().getServices();
}
private MockCFSpace getSpace() throws IOException {
if (params.getOrgName()==null) {
throw errorNoOrgSelected();
}
if (params.getSpaceName()==null) {
throw errorNoSpaceSelected();
}
MockCFSpace space = spacesByName.get(params.getOrgName()+"/"+params.getSpaceName());
if (space==null) {
throw errorSpaceNotFound(params.getOrgName()+"/"+params.getSpaceName());
}
return space;
}
@Override
public List<CFCloudDomain> getDomains() throws Exception {
checkConnection();
return ImmutableList.<CFCloudDomain>copyOf(domainsByName.values());
}
@Override
public List<CFBuildpack> getBuildpacks() throws Exception {
checkConnection();
return ImmutableList.<CFBuildpack>copyOf(buildpacksByName.values());
}
@Override
public List<CFApplication> getApplicationsWithBasicInfo() throws Exception {
checkConnection();
return getSpace().getApplicationsWithBasicInfo();
}
@Override
public CFApplicationDetail getApplication(String appName) throws Exception {
checkConnection();
MockCFApplication app = getSpace().getApplication(appName);
if (app!=null) {
return app.getDetailedInfo();
}
return null;
}
@Override
public Version getApiVersion() {
return apiVersion;
}
@Override
public Version getSupportedApiVersion() {
return supportedApiVersion;
}
@Override
public void deleteApplication(String name) throws Exception {
checkConnection();
if (!getSpace().removeApp(name)) {
throw errorAppNotFound(name);
}
}
@Override
public String getHealthCheck(UUID appGuid) throws Exception {
checkConnection();
MockCFApplication app = getApplication(appGuid);
if (app == null) {
throw errorAppNotFound("GUID: "+appGuid.toString());
} else {
return app.getHealthCheckType();
}
}
private MockCFApplication getApplication(UUID appGuid) throws IOException {
return getSpace().getApplication(appGuid);
}
/**
* Each mock operation that does something requires access to CF should call this
* to ensure that it implicitly check whether the connection is valid.
* <p>
* Operations on 'invalid' connection are expected to throw Exceptions.
* Calling this method makes the operations behave as expected. For example,
* fail when logged out, or when connection was created with invalid credentials.
*/
private void checkConnection() throws Exception {
if (!connected) {
throw errorClientNotConnected();
}
if (validCredentials==null) {
validCredentials = isValidCredentials(params.getUsername(), params.getCredentials());
}
if (!validCredentials) {
throw errorInvalidCredentials();
}
}
private boolean isValidCredentials(String username, CFCredentials credentials) throws Exception {
CFCredentialType type = credentials.getType();
String secret = credentials.getSecret();
if (type==CFCredentialType.PASSWORD) {
if (!credentials.getSecret().equals(validPassword)) {
return false;
}
} else if (type==CFCredentialType.REFRESH_TOKEN) {
if (!secret.equals(FAKE_REFRESH_TOKEN)) {
return false;
}
} else if (type==CFCredentialType.TEMPORARY_CODE) {
if (!checkSsoToken(secret)) {
return false;
}
} else {
return false;
}
//Validation of credentials is expected to update refresh token.
refreshToken.setValue(FAKE_REFRESH_TOKEN);
return true;
}
@Override
public void setHealthCheck(UUID guid, String hcType) throws Exception {
checkConnection();
notImplementedStub();
}
@Override
public List<CFStack> getStacks() throws Exception {
checkConnection();
return ImmutableList.<CFStack>copyOf(stacksByName.values());
}
@Override
public boolean applicationExists(String appName) throws Exception {
checkConnection();
return getSpace().getApplication(appName) !=null;
}
@Override
public void push(CFPushArguments args, CancelationToken cancelationToken) throws Exception {
checkConnection();
System.out.println("Pushing: "+args);
//TODO: should check services exist and raise an error because non-existant services cannot be bound.
MockCFSpace space = getSpace();
MockCFApplication app = new MockCFApplication(MockCloudFoundryClientFactory.this, space, args.getAppName());
app.setBuildpackUrlMaybe(args.getBuildpack());
app.setRoutes(buildRoutes(args));
app.setCommandMaybe(args.getCommand());
app.setDiskQuotaMaybe(args.getDiskQuota());
app.setEnvMaybe(args.getEnv());
app.setMemoryMaybe(args.getMemory());
app.setServicesMaybe(args.getServices());
app.setStackMaybe(args.getStack());
app.setTimeoutMaybe(args.getTimeout());
app.setHealthCheckTypeMaybe(args.getHealthCheckType());
app.setHealthCheckHttpEndpoint(args.getHealthCheckHttpEndpoint());
app.setBits(() -> {
try {
return Files.readAllBytes(args.getApplicationDataAsFile().toPath());
} catch (IOException e) {
return new byte[0];
}
});
space.put(app);
space.getPushCount(app.getName()).increment();
app.start(cancelationToken);
}
private Collection<RouteBinding> buildRoutes(CFPushArguments args) {
List<String> desiredUris = args.getRoutes();
if (desiredUris!=null) {
return desiredUris.stream()
.map(uri -> buildRoute(uri, args))
.collect(Collectors.toList());
}
return ImmutableList.of();
}
private RouteBinding buildRoute(String _uri, CFPushArguments args) {
ParsedUri uri = new ParsedUri(_uri);
boolean randomRoute = args.getRandomRoute();
CFCloudDomainData bestDomain = domainsByName.values().stream()
.filter(domain -> domainCanBeUsedFor(domain, uri))
.max((d1, d2) -> Integer.compare(d1.getName().length(), d2.getName().length()))
.orElse(null);
if (bestDomain==null) {
throw new IllegalStateException("No domain matching the given uri '"+_uri+"' could be found");
}
RouteBinding route = new RouteBinding();
route.setDomain(bestDomain.getName());
route.setHost(bestDomain.splitHost(uri.getHostAndDomain()));
route.setPath(uri.getPath());
route.setPort(uri.getPort());
if (randomRoute) {
if (bestDomain.getType()==CFDomainType.TCP) {
if (route.getPort()==null) {
route.setPort(choosePort());
}
} else if (bestDomain.getType()==CFDomainType.HTTP) {
if (route.getHost()==null) {
route.setHost(chooseHost());
}
}
}
return route;
}
private String chooseHost() {
return RandomStringUtils.randomAlphabetic(8).toLowerCase();
}
private boolean domainCanBeUsedFor(CFCloudDomainData domainData, ParsedUri uri) {
String domain = domainData.getName();
String hostAndDomain = uri.getHostAndDomain();
String host;
if (!hostAndDomain.endsWith(domain)) {
return false;
}
if (domain.length()==hostAndDomain.length()) {
//The uri matches domain precisely
host = null;
} else if (hostAndDomain.charAt(hostAndDomain.length()-domain.length()-1)=='.') {
//THe uri matches as ${host}.${domain}
host = hostAndDomain.substring(0, hostAndDomain.length()-domain.length()-1);
} else {
//Couldn't match this domain to uri
return false;
}
if (domainData.getType()==CFDomainType.TCP) {
return host==null; //TCP routes don't allow setting a host, only a port
} else if (domainData.getType()==CFDomainType.HTTP) {
return uri.getPort()==null; //HTTP routes don't allow setting a port only a host
} else {
throw new IllegalStateException("Unknown domain type: "+domainData.getType());
}
}
@Override
public Map<String, String> getApplicationEnvironment(String appName) throws Exception {
checkConnection();
MockCFApplication app = getSpace().getApplication(appName);
if (app==null) {
throw errorAppNotFound(appName);
}
return ImmutableMap.copyOf(app.getEnv());
}
@Override
public Mono<Void> deleteServiceAsync(String serviceName) {
return Mono.defer(() -> {
try {
checkConnection();
getSpace().deleteService(serviceName);
return Mono.empty();
} catch (Exception e) {
return Mono.error(e);
}
});
}
@Override
public Mono<String> getUserName() {
return Mono.defer(() -> {
try {
checkConnection();
return Mono.just(params.getUsername());
} catch (Exception e) {
return Mono.error(e);
}
});
}
@Override
public String getRefreshToken() {
return refreshToken.getValue();
}
@Override
public Flux<String> getRefreshTokens() {
return LiveExpToFlux.toFlux(refreshToken);
}
}
public void defBuildpacks(String... names) {
for (String n : names) {
defBuildpack(n);
}
}
public MockCFBuildpack defBuildpack(String n) {
MockCFBuildpack it = new MockCFBuildpack(n);
buildpacksByName.put(n, it);
return it;
}
//////////////////////////////////////////////////
// Exception creation methods
protected IOException errorAppNotFound(String detailMessage) throws IOException {
return new IOException("App not found: "+detailMessage);
}
protected IOException errorClientNotConnected() {
return new IOException("CF Client not Connected");
}
protected IOException errorNoOrgSelected() {
return new IOException("No org selected");
}
protected IOException errorNoSpaceSelected() {
return new IOException("No space selected");
}
protected IOException errorSpaceNotFound(String detail) {
return new IOException("Space not found: "+detail);
}
protected IOException errorAppAlreadyExists(String detail) {
return new IOException("App already exists: "+detail);
}
protected Exception errorInvalidCredentials() {
return new Exception("Cannot connect to CF. Invalid credentials.");
}
public void setAppStartDelay(TimeUnit timeUnit, int howMany) {
startDelay = timeUnit.toMillis(howMany);
}
/**
* @return The delay that a simulated 'start' of an app should take before returning. Given in milliseconds.
*/
public long getStartDelay() {
return startDelay;
}
public void setApiVersion(String string) {
apiVersion = new Version(string);
}
public void setSupportedApiVersion(String string) {
supportedApiVersion = new Version(string);
}
public int instanceCount() {
return instances.size();
}
public void changeRefrestToken(String newToken) {
for (MockClient client : instances) {
client.refreshToken.setValue(newToken);
}
}
}

View File

@@ -1,88 +0,0 @@
/*******************************************************************************
* Copyright (c) 2015, 2017 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test.mocks;
import static org.springframework.ide.eclipse.boot.dash.views.sections.BootDashColumn.DEFAULT_PATH;
import static org.springframework.ide.eclipse.boot.dash.views.sections.BootDashColumn.INSTANCES;
import static org.springframework.ide.eclipse.boot.dash.views.sections.BootDashColumn.NAME;
import static org.springframework.ide.eclipse.boot.dash.views.sections.BootDashColumn.PROJECT;
import static org.springframework.ide.eclipse.boot.dash.views.sections.BootDashColumn.RUN_STATE_ICN;
import static org.springframework.ide.eclipse.boot.dash.views.sections.BootDashColumn.TAGS;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.springframework.ide.eclipse.boot.dash.cf.runtarget.CloudFoundryTargetProperties;
import org.springframework.ide.eclipse.boot.dash.model.AbstractRunTarget;
import org.springframework.ide.eclipse.boot.dash.model.BootDashModelContext;
import org.springframework.ide.eclipse.boot.dash.model.BootDashViewModel;
import org.springframework.ide.eclipse.boot.dash.model.RunTargetWithProperties;
import org.springframework.ide.eclipse.boot.dash.api.RunTargetType;
import org.springframework.ide.eclipse.boot.dash.model.runtargettypes.TargetProperties;
import org.springframework.ide.eclipse.boot.dash.views.sections.BootDashColumn;
public class MockRunTarget extends AbstractRunTarget<CloudFoundryTargetProperties> implements RunTargetWithProperties<CloudFoundryTargetProperties> {
private CloudFoundryTargetProperties properties;
private boolean requiresCredentials;
public MockRunTarget(RunTargetType<CloudFoundryTargetProperties> type, CloudFoundryTargetProperties properties) {
this(type, properties, false);
}
public MockRunTarget(RunTargetType<CloudFoundryTargetProperties> type, CloudFoundryTargetProperties properties, boolean requiresCredentials) {
super(type, properties.getRunTargetId());
this.properties = properties;
this.requiresCredentials = requiresCredentials;
}
private final BootDashColumn[] defaultColumns = { RUN_STATE_ICN, NAME, PROJECT, INSTANCES, DEFAULT_PATH, TAGS };
@Override
public BootDashColumn[] getDefaultColumns() {
return defaultColumns;
}
@Override
public MockBootDashModel createSectionModel(BootDashViewModel viewModel) {
return new MockBootDashModel(this, viewModel.getContext(), viewModel);
}
@Override
public boolean canRemove() {
return true;
}
@Override
public boolean canDeployAppsFrom() {
return false;
}
public String get(String prop) {
return properties.get(prop);
}
@Override
public TargetProperties getTargetProperties() {
return properties;
}
@Override
public boolean requiresCredentials() {
return requiresCredentials;
}
@Override
public CloudFoundryTargetProperties getParams() {
return properties;
}
}

View File

@@ -1,76 +0,0 @@
/*******************************************************************************
* Copyright (c) 2015 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test.mocks;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import org.eclipse.jface.resource.ImageDescriptor;
import org.springframework.ide.eclipse.boot.dash.cf.runtarget.CloudFoundryTargetProperties;
import org.springframework.ide.eclipse.boot.dash.di.SimpleDIContext;
import org.springframework.ide.eclipse.boot.dash.model.BootDashModelContext;
import org.springframework.ide.eclipse.boot.dash.model.RunTarget;
import org.springframework.ide.eclipse.boot.dash.model.runtargettypes.AbstractRunTargetType;
import org.springframework.ide.eclipse.boot.dash.model.runtargettypes.TargetProperties;
import org.springsource.ide.eclipse.commons.livexp.core.LiveSetVariable;
import com.google.gson.Gson;
public class MockRunTargetType extends AbstractRunTargetType<CloudFoundryTargetProperties> {
private boolean requiresCredentials;
public MockRunTargetType(SimpleDIContext injections, String name) {
super(injections, name);
}
@Override
public boolean canInstantiate() {
return true;
}
@Override
public CompletableFuture<?> openTargetCreationUi(LiveSetVariable<RunTarget> targets) {
return CompletableFuture.completedFuture(null);
}
@Override
public RunTarget createRunTarget(CloudFoundryTargetProperties properties) {
return new MockRunTarget(this, properties, requiresCredentials);
}
@Override
public ImageDescriptor getIcon() {
return null;
}
public void setRequiresCredentials(boolean requires) {
this.requiresCredentials = requires;
}
@Override
public CloudFoundryTargetProperties parseParams(String serializedTargetParams) {
Gson gson = new Gson();
@SuppressWarnings("unchecked")
Map<String,String> map = gson.fromJson(serializedTargetParams, Map.class);
return new CloudFoundryTargetProperties(new TargetProperties(map, this), this, injections);
}
@Override
public String serialize(CloudFoundryTargetProperties props) {
return props.toJson();
}
@Override
public ImageDescriptor getDisconnectedIcon() {
return null;
}
}

View File

@@ -1,72 +0,0 @@
/*******************************************************************************
* Copyright (c) 2018 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test.mocks;
import org.springframework.ide.eclipse.boot.dash.cf.client.SshHost;
import org.springframework.ide.eclipse.boot.dash.cf.debug.SshTunnel;
import org.springframework.ide.eclipse.boot.dash.util.LogSink;
import org.springsource.ide.eclipse.commons.livexp.core.AbstractDisposable;
public class MockSshTunnel extends AbstractDisposable implements SshTunnel {
boolean disposed = false;
private SshHost sshHost;
private String user;
private String oneTimeCode;
private int remotePort;
private LogSink log;
private int localPort;
public MockSshTunnel(
SshHost sshHost,
String user,
String oneTimeCode,
int remotePort,
LogSink log,
int localPort
) {
this.sshHost = sshHost;
this.user = user;
this.oneTimeCode = oneTimeCode;
this.remotePort = remotePort;
this.log = log;
this.localPort = localPort;
}
public boolean isDisposed() {
return disposed;
}
public SshHost getSshHost() {
return sshHost;
}
public String getUser() {
return user;
}
public String getOneTimeCode() {
return oneTimeCode;
}
public int getRemotePort() {
return remotePort;
}
public LogSink getLog() {
return log;
}
public int getLocalPort() {
return localPort;
}
}

View File

@@ -1,56 +0,0 @@
package org.springframework.ide.eclipse.boot.dash.test.util;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class SslValidationDisabler {
private static boolean installed = false;
public synchronized static void disableSslValidation() throws Exception {
if (installed) {
return;
}
installed = true;
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
}};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
}

View File

@@ -1,97 +0,0 @@
/*******************************************************************************
* Copyright (c) 2015, 2016 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test.util;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Utility for comparing a given 'expected' zip file's contents with
* a 'actual' zip contents.
* <p>
* Two zips are considered equal if they have the same files / folders
* in their table-of contents and each of the files has identical contents.
* <p>
* This differ doesn't actually compare two files directly but rather computes
* a hash of the file contents instead and compares the hashes. So...
* their is a small chance that a difference may not be detected.
*
* @author Kris De Volder
*/
public class ZipDiff {
final Map<String, Long> expectedHashes;
public ZipDiff(InputStream expectedZipData) throws IOException {
expectedHashes = computeHashes(expectedZipData);
}
public Map<String, Long> computeHashes(InputStream expectedZipData) throws IOException {
Map<String, Long> hashes = new HashMap<>();
ZipInputStream zip = new ZipInputStream(expectedZipData);
ZipEntry ze;
byte[] buffer = new byte[1024];
while (null != (ze = zip.getNextEntry())) {
String path = ze.getName();
if (ze.isDirectory()) {
hashes.put(path, -1L);
} else {
CRC32 hasher = new CRC32();
int len;
while ((len = zip.read(buffer)) > 0) {
hasher.update(buffer, 0, len);
}
hashes.put(path, hasher.getValue());
}
}
return hashes;
}
/**
* Read data from 'actualBits', interpret is as a ZipInputStream,
* and compare its contents to the expected contents.
* <p>
* Throws an exception when a difference is found.
*/
public void assertEqual(InputStream actualBits) throws IOException {
Map<String, Long> actualHashes = computeHashes(actualBits);
//Check that everything that is in 'actualBits' was as expected
for (Entry<String, Long> actual : actualHashes.entrySet()) {
if (!expectedHashes.containsKey(actual.getKey())) {
fail("ZipEntry found but not expected: "+actual.getKey());
}
long expectedHash = expectedHashes.get(actual.getKey());
long actualHash = actual.getValue();
if (expectedHash!=actualHash) {
fail("ZipEntry with different hashes: "+actual.getKey()+" "+expectedHash+"!="+actualHash);
}
}
//Check that there's nothing that was expected but was missing from 'actual'
for (String expected : expectedHashes.keySet()) {
if (!actualHashes.containsKey(expected)) {
fail("ZipEntry expected but not found: "+expected);
}
}
}
}

View File

@@ -1,93 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016, 2019 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test.yaml;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.text.Document;
import org.junit.Test;
import org.springframework.ide.eclipse.boot.dash.cf.deployment.AppNameAnnotation;
import org.springframework.ide.eclipse.boot.dash.cf.deployment.AppNameAnnotationModel;
import org.springframework.ide.eclipse.boot.dash.cf.deployment.AppNameReconciler;
import org.springframework.ide.eclipse.editor.support.yaml.ast.YamlASTProvider;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
/**
* Tests for application name reconciler
*
* @author Alex Boyko
*
*/
public class AppNameReconcilerTest {
private void testAppNames(String manifest, String...expectedAppNames) throws Exception {
AppNameReconciler reconciler = new AppNameReconciler(new YamlASTProvider(new Yaml(new SafeConstructor())));
AppNameAnnotationModel annotationModel = new AppNameAnnotationModel("test");
Document doc = new Document(manifest);
reconciler.reconcile(doc, annotationModel, new NullProgressMonitor());
HashSet<String> actualAppNames = new HashSet<>();
for (Iterator<?> itr = annotationModel.getAnnotationIterator(); itr.hasNext();) {
Object o = itr.next();
if (o instanceof AppNameAnnotation) {
actualAppNames.add(((AppNameAnnotation)o).getText());
}
}
assertEquals(new HashSet<>(Arrays.asList(expectedAppNames)), actualAppNames);
}
@Test
public void testSingleAppName() throws Exception {
testAppNames(
"applications:\n" +
"- name: app\n" +
" memory: 512M\n",
"app");
}
@Test
public void testMultipleAppNames() throws Exception {
testAppNames(
"applications:\n" +
"- name: app\n" +
" memory: 512M\n" +
"- name: anotherApp\n" +
" memory: 512M\n" +
"- name: someApp\n" +
" memory: 512M\n",
"app", "anotherApp", "someApp");
}
@Test
public void testNoAppName() throws Exception {
testAppNames(
"applications:\n" +
" memory: 512M\n");
}
@Test
public void testNoAppDueToSyntaxErrorNames() throws Exception {
testAppNames(
"applications:\n" +
"- name: app\n" +
" memory 512M\n" +
"- name: anotherApp\n" +
" memory: 512M\n" +
"- name: someApp\n" +
" memory: 512M\n");
}
}

View File

@@ -1,590 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test.yaml;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.ide.eclipse.boot.dash.cf.client.v2.CFRoute;
import org.springframework.ide.eclipse.boot.dash.cf.client.v2.CFRouteBuilder;
public class CFRouteTests {
public static final List<String> SPRING_CLOUD_DOMAINS = Arrays.<String>asList("springsource.org", "spring.io",
"myowndomain.spring.io", "tcp.spring.io", "spring.framework");
@Test
public void test_domain_host() throws Exception {
CFRoute route = CFRoute.builder().from("myapp.spring.io", SPRING_CLOUD_DOMAINS).build();
Assert.assertEquals("spring.io", route.getDomain());
Assert.assertEquals("myapp", route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals("myapp.spring.io", route.getRoute());
}
@Test
public void test_domain_only() throws Exception {
CFRoute route = CFRoute.builder().from("spring.io", SPRING_CLOUD_DOMAINS).build();
Assert.assertEquals("spring.io", route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals("spring.io", route.getRoute());
}
@Test
public void test_longer_domain_match() throws Exception {
CFRoute route = CFRoute.builder().from("myowndomain.spring.io", SPRING_CLOUD_DOMAINS).build();
Assert.assertEquals("myowndomain.spring.io", route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals("myowndomain.spring.io", route.getRoute());
}
@Test
public void test_longer_domain_nonexisting() throws Exception {
// For domains that do not exist, the first segment is assumed to be the "host"
CFRoute route = CFRoute.builder().from("app.doesnotexist.io", SPRING_CLOUD_DOMAINS).build();
Assert.assertEquals("doesnotexist.io", route.getDomain());
Assert.assertEquals("app",route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals("app.doesnotexist.io", route.getRoute());
}
@Test
public void test_longer_domain_nonexisting_path() throws Exception {
CFRoute route = CFRoute.builder().from("app.doesnotexist.io/withpath", SPRING_CLOUD_DOMAINS).build();
Assert.assertEquals("doesnotexist.io", route.getDomain());
Assert.assertEquals("app",route.getHost());
Assert.assertEquals("/withpath",route.getPath());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals("app.doesnotexist.io/withpath", route.getRoute());
}
@Test
public void test_longer_domain_nonexisting_path_port() throws Exception {
CFRoute route = CFRoute.builder().from("app.doesnotexist.io:60100/withpath", SPRING_CLOUD_DOMAINS).build();
Assert.assertEquals("doesnotexist.io", route.getDomain());
Assert.assertEquals("app",route.getHost());
Assert.assertEquals("/withpath",route.getPath());
Assert.assertEquals(60100, route.getPort());
Assert.assertEquals("app.doesnotexist.io:60100/withpath", route.getRoute());
}
@Test
public void test_longer_domain_match_2() throws Exception {
CFRoute route = CFRoute.builder().from("myapp.myowndomain.spring.io", SPRING_CLOUD_DOMAINS).build();
Assert.assertEquals("myowndomain.spring.io", route.getDomain());
Assert.assertEquals("myapp", route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals("myapp.myowndomain.spring.io", route.getRoute());
}
@Test
public void test_domain_host_path() throws Exception {
CFRoute route = CFRoute.builder().from("myapp.spring.io/appPath", SPRING_CLOUD_DOMAINS).build();
Assert.assertEquals("spring.io", route.getDomain());
Assert.assertEquals("myapp", route.getHost());
Assert.assertEquals("/appPath", route.getPath());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals("myapp.spring.io/appPath", route.getRoute());
}
@Test
public void test_domain_host_path_2() throws Exception {
CFRoute route = CFRoute.builder().from("myapp.spring.io/appPath/additionalSegment", SPRING_CLOUD_DOMAINS)
.build();
Assert.assertEquals("spring.io", route.getDomain());
Assert.assertEquals("myapp", route.getHost());
Assert.assertEquals("/appPath/additionalSegment", route.getPath());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals("myapp.spring.io/appPath/additionalSegment", route.getRoute());
}
@Test
public void test_tcp_port() throws Exception {
CFRoute route = CFRoute.builder().from("tcp.spring.io:9000", SPRING_CLOUD_DOMAINS).build();
Assert.assertEquals("tcp.spring.io", route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals(9000, route.getPort());
Assert.assertEquals("tcp.spring.io:9000", route.getRoute());
}
@Test
public void test_host_path() throws Exception {
CFRoute route = CFRoute.builder().from("justhost/path", SPRING_CLOUD_DOMAINS).build();
Assert.assertNull(route.getDomain());
Assert.assertEquals("justhost",route.getHost());
Assert.assertEquals("/path",route.getPath());
Assert.assertEquals("justhost/path",route.getRoute());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
}
@Test
public void test_routes() throws Exception {
// A CFRoute does not validate route values. It can create any CF route even with wrong domains
// ports, hosts.. This tests that the route builder is parsing an invalid route into different
// components that some other external mechanism (like the CF Java client) can the use to validate
CFRoute route = CFRoute.builder().from("", SPRING_CLOUD_DOMAINS).build();
Assert.assertNull(route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals(CFRoute.EMPTY_ROUTE,route.getRoute());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
route = CFRoute.builder().from(null, SPRING_CLOUD_DOMAINS).build();
Assert.assertNull(route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals(CFRoute.EMPTY_ROUTE,route.getRoute());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
route = CFRoute.builder().from(".", SPRING_CLOUD_DOMAINS).build();
Assert.assertNull(route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals(".",route.getRoute());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
route = CFRoute.builder().from("justhost", SPRING_CLOUD_DOMAINS).build();
Assert.assertNull(route.getDomain());
Assert.assertEquals("justhost",route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals("justhost",route.getRoute());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
route = CFRoute.builder().from("justhost.", SPRING_CLOUD_DOMAINS).build();
Assert.assertNull(route.getDomain());
Assert.assertEquals("justhost",route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals("justhost.",route.getRoute());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
route = CFRoute.builder().from(".justdomain", SPRING_CLOUD_DOMAINS).build();
Assert.assertEquals("justdomain",route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals(".justdomain",route.getRoute());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
route = CFRoute.builder().from("..justdomain", SPRING_CLOUD_DOMAINS).build();
Assert.assertEquals(".justdomain",route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals("..justdomain",route.getRoute());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
route = CFRoute.builder().from("/justpath/morepath", SPRING_CLOUD_DOMAINS).build();
Assert.assertNull(route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertEquals("/justpath/morepath",route.getPath());
Assert.assertEquals("/justpath/morepath",route.getRoute());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
route = CFRoute.builder().from("/", SPRING_CLOUD_DOMAINS).build();
Assert.assertNull(route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertEquals("/",route.getPath());
Assert.assertEquals("/",route.getRoute());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
}
@Test
public void test_incorrect_ports() throws Exception {
CFRoute route = CFRoute.builder().from("myapp.spring.io:notAn1nt3g3r", SPRING_CLOUD_DOMAINS).build();
Assert.assertEquals("spring.io",route.getDomain());
Assert.assertEquals("myapp",route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals("myapp.spring.io:notAn1nt3g3r",route.getRoute());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
// Test parsing around the first encountered ':'
route = CFRoute.builder().from("https://myapp.spring.io", SPRING_CLOUD_DOMAINS).build();
Assert.assertEquals("https://myapp.spring.io",route.getRoute());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
route = CFRoute.builder().from("tcp.spring.io:8000:9000", SPRING_CLOUD_DOMAINS).build();
// Only one ':' is allowed. it should not be able to parse a port if more than ':' is encountered
Assert.assertEquals("tcp.spring.io:8000:9000",route.getRoute());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
route = CFRoute.builder().from("myapp.spring.io:8000/", SPRING_CLOUD_DOMAINS).build();
Assert.assertEquals("spring.io",route.getDomain());
Assert.assertEquals("myapp",route.getHost());
Assert.assertEquals("/",route.getPath());
Assert.assertEquals("myapp.spring.io:8000/",route.getRoute());
Assert.assertEquals(8000, route.getPort());
}
@Test
public void test_incorrect_paths() throws Exception {
CFRoute route = CFRoute.builder().from("myapp.spring.io//path", SPRING_CLOUD_DOMAINS).build();
Assert.assertEquals("spring.io",route.getDomain());
Assert.assertEquals("myapp",route.getHost());
Assert.assertEquals("//path",route.getPath());
Assert.assertEquals("myapp.spring.io//path",route.getRoute());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
route = CFRoute.builder().from("myapp.spring.io/", SPRING_CLOUD_DOMAINS).build();
Assert.assertEquals("spring.io",route.getDomain());
Assert.assertEquals("myapp",route.getHost());
Assert.assertEquals("/",route.getPath());
Assert.assertEquals("myapp.spring.io/",route.getRoute());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
}
@Test
public void parse_null_domain() throws Exception {
String domain = CFRouteBuilder.findDomain("", SPRING_CLOUD_DOMAINS);
Assert.assertNull(domain);
domain = CFRouteBuilder.findDomain(null, SPRING_CLOUD_DOMAINS);
Assert.assertNull(domain);
domain = CFRouteBuilder.findDomain(".", SPRING_CLOUD_DOMAINS);
Assert.assertNull(domain);
domain = CFRouteBuilder.findDomain(".cfapps", SPRING_CLOUD_DOMAINS);
Assert.assertNull(domain);
domain = CFRouteBuilder.findDomain("cfapps.", SPRING_CLOUD_DOMAINS);
Assert.assertNull(domain);
domain = CFRouteBuilder.findDomain("...", SPRING_CLOUD_DOMAINS);
Assert.assertNull(domain);
domain = CFRouteBuilder.findDomain("..cfapps..", SPRING_CLOUD_DOMAINS);
Assert.assertNull(domain);
domain = CFRouteBuilder.findDomain(".cfapps..", SPRING_CLOUD_DOMAINS);
Assert.assertNull(domain);
domain = CFRouteBuilder.findDomain("..cfapps.", SPRING_CLOUD_DOMAINS);
Assert.assertNull(domain);
}
@Test
public void parse_valid_domain() throws Exception {
// These exist
String domain = CFRouteBuilder.findDomain("spring.io", SPRING_CLOUD_DOMAINS);
Assert.assertEquals("spring.io", domain);
domain = CFRouteBuilder.findDomain(".spring.io", SPRING_CLOUD_DOMAINS);
Assert.assertEquals("spring.io", domain);
domain = CFRouteBuilder.findDomain("..spring.io", SPRING_CLOUD_DOMAINS);
Assert.assertEquals("spring.io", domain);
domain = CFRouteBuilder.findDomain("myapp.spring.io", SPRING_CLOUD_DOMAINS);
Assert.assertEquals("spring.io", domain);
domain = CFRouteBuilder.findDomain("myowndomain.spring.io", SPRING_CLOUD_DOMAINS);
Assert.assertEquals("myowndomain.spring.io", domain);
domain = CFRouteBuilder.findDomain("myapp.myowndomain.spring.io", SPRING_CLOUD_DOMAINS);
Assert.assertEquals("myowndomain.spring.io", domain);
}
@Test
public void parse_invalid_domain() throws Exception {
// These variations of existing domains don't exist
String domain = CFRouteBuilder.findDomain("spring.io.", SPRING_CLOUD_DOMAINS);
Assert.assertNull(domain);
domain = CFRouteBuilder.findDomain("spring.cfapps.io", SPRING_CLOUD_DOMAINS);
Assert.assertNull(domain);
domain = CFRouteBuilder.findDomain("spring.io.cfapps", SPRING_CLOUD_DOMAINS);
Assert.assertNull(domain);
domain = CFRouteBuilder.findDomain("unknown", SPRING_CLOUD_DOMAINS);
Assert.assertNull(domain);
domain = CFRouteBuilder.findDomain("unknown.domain.io", SPRING_CLOUD_DOMAINS);
Assert.assertNull(domain);
}
@Test
public void bug_142279275_parse_hostAndPathSameName() throws Exception {
// Fixes Pivotal Tracker item 142279275
CFRoute route = CFRoute.builder().from("hello-user.myowndomain.spring.io/hello", SPRING_CLOUD_DOMAINS).build();
Assert.assertEquals("hello-user", route.getHost());
Assert.assertEquals("myowndomain.spring.io", route.getDomain());
Assert.assertEquals("/hello", route.getPath());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals("hello-user.myowndomain.spring.io/hello", route.getRoute());
}
@Test
public void build_route_value_empty() throws Exception {
String val = CFRouteBuilder.buildRouteVal(null, null, null, CFRoute.NO_PORT);
Assert.assertEquals(CFRoute.EMPTY_ROUTE, val);
val = CFRouteBuilder.buildRouteVal("", "", "", CFRoute.NO_PORT);
Assert.assertEquals(CFRoute.EMPTY_ROUTE, val);
}
@Test
public void build_route_value() throws Exception {
String val = CFRouteBuilder.buildRouteVal("appHost", null, null, CFRoute.NO_PORT);
Assert.assertEquals("appHost", val);
val = CFRouteBuilder.buildRouteVal(null, "cfapps.io", "", CFRoute.NO_PORT);
Assert.assertEquals("cfapps.io", val);
val = CFRouteBuilder.buildRouteVal("appHost", "cfapps.io", "", CFRoute.NO_PORT);
Assert.assertEquals("appHost.cfapps.io", val);
val = CFRouteBuilder.buildRouteVal(null, null, "/path/to/app", CFRoute.NO_PORT);
Assert.assertEquals("/path/to/app", val);
val = CFRouteBuilder.buildRouteVal(null, null, "/path/to/app", 8000);
Assert.assertEquals(":8000/path/to/app", val);
val = CFRouteBuilder.buildRouteVal(null, null, null, 60101);
Assert.assertEquals(":60101", val);
val = CFRouteBuilder.buildRouteVal("appHost", "cfapps.io", "/path/to/app", CFRoute.NO_PORT);
Assert.assertEquals("appHost.cfapps.io/path/to/app", val);
val = CFRouteBuilder.buildRouteVal("appHost", "cfapps.io", "/path/to/app", 60101);
Assert.assertEquals("appHost.cfapps.io:60101/path/to/app", val);
}
@Test
public void test_build_route_from_domain() throws Exception {
CFRoute route = CFRoute.builder().domain("spring.io").build();
Assert.assertEquals("spring.io", route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals("spring.io", route.getRoute());
}
@Test
public void test_build_route_from_nonexisting_domain() throws Exception {
CFRoute route = CFRoute.builder().domain("not.exist.io").build();
Assert.assertEquals("not.exist.io", route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals("not.exist.io", route.getRoute());
}
@Test
public void test_build_route_from_null_domain() throws Exception {
CFRoute route = CFRoute.builder().domain(null).build();
Assert.assertNull(route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals(CFRoute.EMPTY_ROUTE, route.getRoute());
}
@Test
public void test_build_route_from_empty_domain() throws Exception {
CFRoute route = CFRoute.builder().domain("").build();
Assert.assertEquals("",route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals(CFRoute.EMPTY_ROUTE,route.getRoute());
}
@Test
public void test_build_route_from_host() throws Exception {
CFRoute route = CFRoute.builder().host("myapp").build();
Assert.assertNull(route.getDomain());
Assert.assertNull(route.getPath());
Assert.assertEquals("myapp", route.getHost());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals("myapp", route.getRoute());
}
@Test
public void test_build_route_from_null_host() throws Exception {
CFRoute route = CFRoute.builder().host(null).build();
Assert.assertNull(route.getDomain());
Assert.assertNull(route.getPath());
Assert.assertNull(route.getHost());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals(CFRoute.EMPTY_ROUTE, route.getRoute());
}
@Test
public void test_build_route_from_empty_host() throws Exception {
CFRoute route = CFRoute.builder().host("").build();
Assert.assertNull(route.getDomain());
Assert.assertNull(route.getPath());
Assert.assertEquals("",route.getHost());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals(CFRoute.EMPTY_ROUTE, route.getRoute());
}
@Test
public void test_build_route_from_domain_host() throws Exception {
CFRoute route = CFRoute.builder().domain("spring.io").host("myapp").build();
Assert.assertEquals("spring.io", route.getDomain());
Assert.assertEquals("myapp", route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals("myapp.spring.io", route.getRoute());
}
@Test
public void test_build_route_from_path() throws Exception {
CFRoute route = CFRoute.builder().path("/path").build();
Assert.assertNull(route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertEquals("/path",route.getPath());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals("/path", route.getRoute());
}
@Test
public void test_build_route_from_path_2() throws Exception {
CFRoute route = CFRoute.builder().path("/path/additional").build();
Assert.assertNull(route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertEquals("/path/additional",route.getPath());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals("/path/additional", route.getRoute());
}
@Test
public void test_build_route_from_path_3() throws Exception {
CFRoute route = CFRoute.builder().path("/path/").build();
Assert.assertNull(route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertEquals("/path/",route.getPath());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals("/path/", route.getRoute());
}
@Test
public void test_build_route_from_domain_path() throws Exception {
CFRoute route = CFRoute.builder().path("/mypath").domain("spring.io").build();
Assert.assertEquals("spring.io",route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertEquals("/mypath",route.getPath());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals("spring.io/mypath", route.getRoute());
}
@Test
public void test_build_route_from_host_path() throws Exception {
CFRoute route = CFRoute.builder().path("/mypath").host("myapp").build();
Assert.assertNull(route.getDomain());
Assert.assertEquals("myapp",route.getHost());
Assert.assertEquals("/mypath",route.getPath());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals("myapp/mypath", route.getRoute());
}
@Test
public void test_build_route_from_host_path_samename() throws Exception {
CFRoute route = CFRoute.builder().path("/myapp").host("myapp").build();
Assert.assertNull(route.getDomain());
Assert.assertEquals("myapp",route.getHost());
Assert.assertEquals("/myapp",route.getPath());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals("myapp/myapp", route.getRoute());
}
@Test
public void test_build_route_from_host_path_port() throws Exception {
CFRoute route = CFRoute.builder().path("/mypath").host("myapp").port(8000).build();
Assert.assertNull(route.getDomain());
Assert.assertEquals("myapp",route.getHost());
Assert.assertEquals("/mypath",route.getPath());
Assert.assertEquals(8000, route.getPort());
Assert.assertEquals("myapp:8000/mypath", route.getRoute());
}
@Test
public void test_build_route_from_domain_path_port() throws Exception {
CFRoute route = CFRoute.builder().path("/mypath").domain("spring.io").port(8000).build();
Assert.assertEquals("spring.io", route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertEquals("/mypath",route.getPath());
Assert.assertEquals(8000, route.getPort());
Assert.assertEquals("spring.io:8000/mypath", route.getRoute());
}
@Test
public void test_build_route_from_port() throws Exception {
CFRoute route = CFRoute.builder().port(8000).build();
Assert.assertNull(route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals(8000, route.getPort());
Assert.assertEquals(":8000", route.getRoute());
}
@Test
public void test_build_route_from_no_port() throws Exception {
CFRoute route = CFRoute.builder().port(CFRoute.NO_PORT).build();
Assert.assertNull(route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals(CFRoute.EMPTY_ROUTE, route.getRoute());
}
@Test
public void test_build_route_from_no_port_2() throws Exception {
CFRoute route = CFRoute.builder().port(-1).build();
Assert.assertNull(route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals(CFRoute.NO_PORT, route.getPort());
Assert.assertEquals(CFRoute.EMPTY_ROUTE, route.getRoute());
}
@Test
public void test_tcp_port_building() throws Exception {
CFRoute route = CFRoute.builder().domain("tcp.spring.io").port(8000).build();
Assert.assertEquals("tcp.spring.io",route.getDomain());
Assert.assertNull(route.getHost());
Assert.assertNull(route.getPath());
Assert.assertEquals(8000, route.getPort());
Assert.assertEquals("tcp.spring.io:8000", route.getRoute());
}
@Test
public void test_complete() throws Exception {
CFRoute route = CFRoute.builder().domain("spring.io").host("myapp").path("/mypath/additional").port(8000).build();
Assert.assertEquals("spring.io",route.getDomain());
Assert.assertEquals("myapp", route.getHost());
Assert.assertEquals("/mypath/additional", route.getPath());
Assert.assertEquals(8000, route.getPort());
Assert.assertEquals("myapp.spring.io:8000/mypath/additional", route.getRoute());
}
}

View File

@@ -1,173 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016, 2017 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test.yaml;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.Map;
import org.junit.Test;
import org.springframework.ide.eclipse.boot.dash.cf.deployment.ApplicationManifestHandler;
import org.springframework.ide.eclipse.boot.dash.cf.deployment.CloudApplicationDeploymentProperties;
import org.springsource.ide.eclipse.commons.frameworks.core.util.IOUtil;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.DumperOptions.FlowStyle;
import org.yaml.snakeyaml.DumperOptions.LineBreak;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.representer.Representer;
/**
* Tests for generating YAML files from {@link CloudApplicationDeploymentProperties}
*
* @author Alex Boyko
*
*/
public class DeploymentProperties2YamlTest {
private static void testDeploymentProperties(CloudApplicationDeploymentProperties props, String expectedYamlFilePath) throws Exception {
Map<Object, Object> map = ApplicationManifestHandler.toYaml(props, ManifestCompareMergeTests.createCloudData());
DumperOptions options = new DumperOptions();
options.setExplicitStart(true);
options.setCanonical(false);
options.setPrettyFlow(true);
options.setDefaultFlowStyle(FlowStyle.BLOCK);
options.setLineBreak(LineBreak.getPlatformLineBreak());
String generatedManifest = new Yaml(new SafeConstructor(), new Representer(options), options).dump(map);
File yamlFile = ManifestCompareMergeTests.getTestFile(expectedYamlFilePath);
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(yamlFile);
assertEquals(IOUtil.toString(inputStream).trim(), generatedManifest.trim());
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
@Test
public void test_no_route_1() throws Exception {
CloudApplicationDeploymentProperties props = new CloudApplicationDeploymentProperties();
props.setAppName("app");
props.setMemory(512);
props.setUris(null);
testDeploymentProperties(props, "manifest-generate-data/no-route-1.yml");
}
@Test
public void test_uri_1() throws Exception {
CloudApplicationDeploymentProperties props = new CloudApplicationDeploymentProperties();
props.setAppName("app");
props.setMemory(512);
props.setUris(Arrays.asList("app.springsource.org"));
testDeploymentProperties(props, "manifest-generate-data/uri-1.yml");
}
@Test
public void test_uri_2() throws Exception {
CloudApplicationDeploymentProperties props = new CloudApplicationDeploymentProperties();
props.setAppName("app");
props.setMemory(512);
props.setUris(Arrays.asList("app-1.springsource.org", "app-2.spring.io"));
testDeploymentProperties(props, "manifest-generate-data/uri-2.yml");
}
@Test
public void test_uri_3() throws Exception {
CloudApplicationDeploymentProperties props = new CloudApplicationDeploymentProperties();
props.setAppName("app");
props.setMemory(512);
props.setUris(Arrays.asList("app-1.springsource.org"));
testDeploymentProperties(props, "manifest-generate-data/uri-3.yml");
}
@Test
public void test_no_hostname_1() throws Exception {
CloudApplicationDeploymentProperties props = new CloudApplicationDeploymentProperties();
props.setAppName("app");
props.setMemory(512);
props.setUris(Arrays.asList("springsource.org"));
testDeploymentProperties(props, "manifest-generate-data/no-hostname-1.yml");
}
@Test
public void test_no_hostname_2() throws Exception {
CloudApplicationDeploymentProperties props = new CloudApplicationDeploymentProperties();
props.setAppName("app");
props.setMemory(512);
props.setUris(Arrays.asList("springsource.org", "spring.io"));
testDeploymentProperties(props, "manifest-generate-data/no-hostname-2.yml");
}
@Test
public void test_command_1() throws Exception {
CloudApplicationDeploymentProperties props = new CloudApplicationDeploymentProperties();
props.setAppName("app");
props.setMemory(512);
props.setCommand("my-command");
props.setUris(Arrays.asList("app.springsource.org"));
testDeploymentProperties(props, "manifest-generate-data/command-1.yml");
}
@Test
public void test_stack_1() throws Exception {
CloudApplicationDeploymentProperties props = new CloudApplicationDeploymentProperties();
props.setAppName("app");
props.setMemory(512);
props.setStack("my-stack");
props.setUris(Arrays.asList("app.springsource.org"));
testDeploymentProperties(props, "manifest-generate-data/stack-1.yml");
}
@Test
public void test_health_check_http() throws Exception {
CloudApplicationDeploymentProperties props = new CloudApplicationDeploymentProperties();
props.setAppName("app");
props.setMemory(512);
props.setHealthCheckType("http");
props.setHealthCheckHttpEndpoint("/testhealth");
props.setUris(Arrays.asList("app.springsource.org"));
testDeploymentProperties(props, "manifest-generate-data/health-check-http.yml");
}
@Test
public void test_health_check_process() throws Exception {
CloudApplicationDeploymentProperties props = new CloudApplicationDeploymentProperties();
props.setAppName("app");
props.setMemory(512);
props.setHealthCheckType("process");
props.setUris(Arrays.asList("app.springsource.org"));
testDeploymentProperties(props, "manifest-generate-data/health-check-process.yml");
}
@Test
public void test_health_check_port() throws Exception {
CloudApplicationDeploymentProperties props = new CloudApplicationDeploymentProperties();
props.setAppName("app");
props.setMemory(512);
props.setHealthCheckType("port");
props.setUris(Arrays.asList("app.springsource.org"));
testDeploymentProperties(props, "manifest-generate-data/health-check-port.yml");
}
}

View File

@@ -1,477 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016, 2017 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.dash.test.yaml;
import static org.junit.Assert.assertEquals;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.junit.Test;
import org.springframework.ide.eclipse.boot.dash.cf.deployment.ApplicationManifestHandler;
import org.springframework.ide.eclipse.boot.dash.cf.deployment.CloudApplicationDeploymentProperties;
import org.springframework.ide.eclipse.boot.dash.cloudfoundry.deployment.DeploymentProperties;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
/**
* Tests for parsing YAML deployment manifest into
* {@link CloudApplicationDeploymentProperties}
*
* @author Alex Boyko
*
*/
public class Yaml2DeploymentPropertiesTest {
private static CloudApplicationDeploymentProperties readDeploymentPropertiesFile(final String filePath) throws Exception {
ApplicationManifestHandler handler = new ApplicationManifestHandler(null, ManifestCompareMergeTests.createCloudData()) {
@Override
protected InputStream getInputStream() throws Exception {
return new FileInputStream(ManifestCompareMergeTests.getTestFile(filePath));
}
};
return handler.load(new NullProgressMonitor()).get(0);
}
@Test
public void test_health_check_process() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/health-check-process.yml");
assertEquals("Health check types not equal", "process", props.getHealthCheckType());
}
@Test
public void test_health_check_port() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/health-check-port.yml");
assertEquals("Health check types not equal", "port", props.getHealthCheckType());
}
@Test
public void test_health_check_http() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/health-check-http.yml");
assertEquals("Health check types not equal", "http", props.getHealthCheckType());
assertEquals("Health check http endpoints not equal", "/testhealth", props.getHealthCheckHttpEndpoint());
}
@Test
public void test_no_route_1() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/no-route-1.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>();
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_no_route_2() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/no-route-2.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>();
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_no_route_3() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/no-route-3.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>();
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_no_route_4() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/no-route-4.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>();
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_no_route_5() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/no-route-5.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>();
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_no_hostname_1() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/no-hostname-1.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Collections.singletonList("my-app.springsource.org"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_no_hostname_2() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/no-hostname-2.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Collections.singletonList("my-app.springsource.org"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_no_hostname_3() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/no-hostname-3.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Collections.singletonList("my-app.springsource.org"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_no_hostname_4() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/no-hostname-4.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Collections.singletonList("springsource.org"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_no_hostname_5() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/no-hostname-5.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Collections.singletonList("springsource.org"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_no_hostname_6() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/no-hostname-6.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Arrays.asList("springsource.org", "spring.framework"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_random_route_1() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/random-route-1.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Collections.singletonList("my-app.springsource.org"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_random_route_2() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/random-route-2.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Collections.singletonList("my-app.springsource.org"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_random_route_3() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/random-route-3.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
assertEquals(1, uris.size());
String uri = uris.iterator().next();
String host = uri.substring(0, uri.indexOf('.'));
HashSet<String> expected = new HashSet<>(Collections.singletonList("springsource.org"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_random_route_4() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/random-route-4.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
assertEquals(1, uris.size());
String uri = uris.iterator().next();
String host = uri.substring(0, uri.indexOf('.'));
HashSet<String> expected = new HashSet<>(Collections.singletonList("springsource.org"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_random_route_5() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/random-route-5.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
Set<String> expected = ImmutableSet.of("spring.io", "spring.framework");
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_domains_1() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/domains-1.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Collections.singletonList("my-app.spring.io"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_domains_2() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/domains-2.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Collections.singletonList("my-app.springsource.org"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_domains_3() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/domains-3.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Collections.singletonList("my-app.spring.framework"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_domains_4() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/domains-4.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Collections.singletonList("my-app.spring.io"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_domains_5() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/domains-5.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Arrays.asList("my-app.spring.framework", "my-app.springsource.org"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_domains_6() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/domains-6.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Collections.singletonList("my-app.spring.what"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_domains_7() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/domains-7.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Arrays.asList("my-app.springsource.org", "my-app.spring.framework", "my-app.spring.io"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_domains_8() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/domains-8.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Arrays.asList("my-app.springsource.org", "my-app.spring.framework", "my-app.spring.io"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_domains_9() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/domains-9.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Arrays.asList("my-app.springsource.org", "my-app.spring.framework", "my-app.spring.io"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_hosts_1() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/hosts-1.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Arrays.asList("app.springsource.org"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_hosts_2() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/hosts-2.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Arrays.asList("my-app.springsource.org"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_hosts_3() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/hosts-3.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Arrays.asList("my-app.springsource.org"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_hosts_4() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/hosts-4.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Arrays.asList("my-app.springsource.org"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_hosts_5() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/hosts-5.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Arrays.asList("my-app-1.springsource.org", "my-app-2.springsource.org", "my-app-3.springsource.org"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_hosts_6() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/hosts-6.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Arrays.asList("my-app-1.springsource.org", "my-app-2.springsource.org",
"my-app-3.springsource.org", "my-root-2.springsource.org", "my-root-3.springsource.org"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_uris_1() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/uris-1.yml");
HashSet<String> uris = new HashSet<>(props.getUris());
HashSet<String> expected = new HashSet<>(Arrays.asList("my-app-1.springsource.org", "my-app-2.springsource.org",
"my-app-3.springsource.org", "my-app-1.spring.io", "my-app-2.spring.io", "my-app-3.spring.io",
"my-app-1.spring.framework", "my-app-2.spring.framework", "my-app-3.spring.framework"));
assertEquals("Uris sets not equal", expected, uris);
}
@Test
public void test_root_1() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/root-1.yml");
assertEquals("app", props.getAppName());
assertEquals(1024, props.getMemory());
assertEquals(new HashSet<>(Arrays.asList("app.spring.io")), props.getUris());
}
@Test
public void test_command_1() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/command-1.yml");
assertEquals("mycommand", props.getCommand());
}
@Test
public void test_stack_1() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/stack-1.yml");
assertEquals("stack1", props.getStack());
}
@Test
public void test_memory_1() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/memory-1.yml");
assertEquals("Uris sets not equal", DeploymentProperties.DEFAULT_MEMORY, props.getMemory());
}
@Test
public void test_memory_2() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/memory-2.yml");
assertEquals("Uris sets not equal", 768, props.getMemory());
}
@Test
public void test_memory_3() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/memory-3.yml");
assertEquals("Uris sets not equal", 768, props.getMemory());
}
@Test
public void test_memory_4() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/memory-4.yml");
assertEquals("Uris sets not equal", 768, props.getMemory());
}
@Test
public void test_memory_5() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/memory-5.yml");
assertEquals("Uris sets not equal", 1024, props.getMemory());
}
@Test
public void test_memory_6() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/memory-6.yml");
assertEquals("Uris sets not equal", 1024, props.getMemory());
}
@Test(expected=CoreException.class)
public void test_memory_7() throws Exception {
readDeploymentPropertiesFile("manifest-parse-data/memory-7.yml");
}
@Test(expected=CoreException.class)
public void test_memory_8() throws Exception {
readDeploymentPropertiesFile("manifest-parse-data/memory-8.yml");
}
@Test
public void test_memory_9() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/memory-9.yml");
assertEquals("Uris sets not equal", 3072, props.getMemory());
}
@Test
public void test_memory_10() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/memory-10.yml");
assertEquals("Uris sets not equal", 4096, props.getMemory());
}
@Test
public void test_memory_11() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile("manifest-parse-data/memory-11.yml");
assertEquals("Uris sets not equal", 1500, props.getMemory());
}
@Test
public void test_routes_no_route() throws Exception {
// Manifest has a route but if "no-route" is also present, test that
// list of URI is empty in the props
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile(
"manifest-generate-data/routes-no-route.yml");
assertEquals("Routes and URIs not equal", ImmutableList.of(), ImmutableList.copyOf(props.getUris()));
}
@Test
public void test_routes_1() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile(
"manifest-parse-data/routes-1.yml");
assertEquals("Routes not equal", ImmutableSet.of("my-route.springsource.org"), ImmutableSet.copyOf(props.getUris()));
}
@Test
public void test_routes_2() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile(
"manifest-parse-data/routes-2.yml");
assertEquals("Routes not equal", ImmutableSet.of("my-route-1.springsource.org", "my-route-2.springsource.org"), ImmutableSet.copyOf(props.getUris()));
}
@Test
public void test_routes_3() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile(
"manifest-parse-data/routes-3.yml");
assertEquals("Routes not equal", ImmutableSet.of(), ImmutableSet.copyOf(props.getUris()));
}
@Test
public void test_routes_4() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile(
"manifest-parse-data/routes-4.yml");
assertEquals("Routes not equal", ImmutableSet.of("my-route-1.springsource.org", "my-route-2.springsource.org"), ImmutableSet.copyOf(props.getUris()));
}
@Test
public void test_routes_5() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile(
"manifest-parse-data/routes-5.yml");
assertEquals("Routes not equal", ImmutableSet.of("my-route-1.springsource.org", "my-route-2.springsource.org",
"my-root-route-1.springsource.org"), ImmutableSet.copyOf(props.getUris()));
}
@Test
public void test_routes_6() throws Exception {
CloudApplicationDeploymentProperties props = readDeploymentPropertiesFile(
"manifest-parse-data/routes-6.yml");
assertEquals("Routes not equal", ImmutableSet.of("my-route-1.invaliddomain.org", "my-route-2.springsource.org"), ImmutableSet.copyOf(props.getUris()));
}
}