Repository: incubator-brooklyn Updated Branches: refs/heads/master 6a8e89f4d -> 015b5cdf5
expand assertions and http assertions for string containment, updating rest tests Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/036ba79a Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/036ba79a Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/036ba79a Branch: refs/heads/master Commit: 036ba79ae3c63c5fa078f73cc1b77cbb854e7631 Parents: 74f7295 Author: Alex Heneveld <[email protected]> Authored: Tue Nov 10 14:09:38 2015 +0000 Committer: Alex Heneveld <[email protected]> Committed: Tue Nov 10 14:30:29 2015 +0000 ---------------------------------------------------------------------- .../ApplicationResourceIntegrationTest.java | 15 +-- .../rest/client/BrooklynApiRestClientTest.java | 37 +++--- .../rest/resources/LocationResource.java | 7 +- .../rest/BrooklynRestApiLauncherTest.java | 15 ++- .../rest/resources/ApplicationResourceTest.java | 10 +- .../rest/resources/EntityResourceTest.java | 8 +- .../rest/resources/SensorResourceTest.java | 4 +- .../rest/resources/ServerShutdownTest.java | 4 +- .../org/apache/brooklyn/test/HttpTestUtils.java | 7 +- .../java/org/apache/brooklyn/test/Asserts.java | 133 +++++++++++++++++++ .../apache/brooklyn/util/http/HttpAsserts.java | 46 +++++-- .../org/apache/brooklyn/test/AssertsTest.java | 74 +++++++++++ 12 files changed, 293 insertions(+), 67 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/036ba79a/usage/rest-client/src/test/java/org/apache/brooklyn/rest/client/ApplicationResourceIntegrationTest.java ---------------------------------------------------------------------- diff --git a/usage/rest-client/src/test/java/org/apache/brooklyn/rest/client/ApplicationResourceIntegrationTest.java b/usage/rest-client/src/test/java/org/apache/brooklyn/rest/client/ApplicationResourceIntegrationTest.java index 3679975..4db359b 100644 --- a/usage/rest-client/src/test/java/org/apache/brooklyn/rest/client/ApplicationResourceIntegrationTest.java +++ b/usage/rest-client/src/test/java/org/apache/brooklyn/rest/client/ApplicationResourceIntegrationTest.java @@ -22,18 +22,10 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; -import java.net.URL; import java.util.Collection; import javax.ws.rs.core.Response; -import org.eclipse.jetty.server.Server; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; import org.apache.brooklyn.api.entity.Application; import org.apache.brooklyn.api.mgmt.ManagementContext; import org.apache.brooklyn.core.entity.StartableApplication; @@ -49,6 +41,13 @@ import org.apache.brooklyn.rest.domain.EntitySummary; import org.apache.brooklyn.rest.domain.SensorSummary; import org.apache.brooklyn.test.Asserts; import org.apache.brooklyn.util.time.Duration; +import org.eclipse.jetty.server.Server; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableMap; http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/036ba79a/usage/rest-client/src/test/java/org/apache/brooklyn/rest/client/BrooklynApiRestClientTest.java ---------------------------------------------------------------------- diff --git a/usage/rest-client/src/test/java/org/apache/brooklyn/rest/client/BrooklynApiRestClientTest.java b/usage/rest-client/src/test/java/org/apache/brooklyn/rest/client/BrooklynApiRestClientTest.java index 993673c..fa738d8 100644 --- a/usage/rest-client/src/test/java/org/apache/brooklyn/rest/client/BrooklynApiRestClientTest.java +++ b/usage/rest-client/src/test/java/org/apache/brooklyn/rest/client/BrooklynApiRestClientTest.java @@ -18,20 +18,11 @@ */ package org.apache.brooklyn.rest.client; -import java.net.URL; import java.util.List; import java.util.Map; import javax.ws.rs.core.Response; -import org.apache.brooklyn.test.HttpTestUtils; -import org.eclipse.jetty.server.Server; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; import org.apache.brooklyn.api.entity.Application; import org.apache.brooklyn.api.mgmt.ManagementContext; import org.apache.brooklyn.core.entity.Entities; @@ -44,7 +35,15 @@ import org.apache.brooklyn.rest.BrooklynRestApiLauncherTest; import org.apache.brooklyn.rest.domain.ApplicationSummary; import org.apache.brooklyn.rest.domain.CatalogLocationSummary; import org.apache.brooklyn.rest.security.provider.TestSecurityProvider; +import org.apache.brooklyn.test.Asserts; +import org.apache.brooklyn.util.http.HttpAsserts; import org.eclipse.jetty.server.NetworkConnector; +import org.eclipse.jetty.server.Server; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; @Test public class BrooklynApiRestClientTest { @@ -107,29 +106,29 @@ public class BrooklynApiRestClientTest { public void testApplicationApiCreate() throws Exception { Response r1 = api.getApplicationApi().createFromYaml("name: test-1234\n" + "services: [ { type: "+TestEntity.class.getName()+" } ]"); - HttpTestUtils.assertHealthyStatusCode(r1.getStatus()); + HttpAsserts.assertHealthyStatusCode(r1.getStatus()); log.info("creation result: "+r1.getEntity()); List<ApplicationSummary> apps = api.getApplicationApi().list(null); log.info("apps with test: "+apps); - Assert.assertTrue(apps.toString().contains("test-1234"), "should have had test-1234 as an app; instead: "+apps); + Asserts.assertStringContains(apps.toString(), "test-1234"); } public void testApplicationApiHandledError() throws Exception { Response r1 = api.getApplicationApi().createFromYaml("name: test"); - Assert.assertTrue(r1.getStatus()/100 != 2, "needed an unhealthy status, not "+r1.getStatus()); - Object entity = r1.getEntity(); - Assert.assertTrue(entity.toString().indexOf("Unrecognized application blueprint format: no services defined")>=0, - "Missing expected text in response: "+entity.toString()); + HttpAsserts.assertNotHealthyStatusCode(r1.getStatus()); + // new-style messages first, old-style messages after (during switch to TypePlanTransformer) + Asserts.assertStringContainsAtLeastOne(r1.getEntity().toString().toLowerCase(), + "invalid plan", "no services"); + Asserts.assertStringContainsAtLeastOne(r1.getEntity().toString().toLowerCase(), + "format could not be recognized", "Unrecognized application blueprint format"); } public void testApplicationApiThrownError() throws Exception { try { ApplicationSummary summary = api.getApplicationApi().get("test-5678"); - Assert.fail("Should have thrown, not given: "+summary); + Asserts.shouldHaveFailedPreviously("got "+summary); } catch (Exception e) { - e.printStackTrace(); - Assert.assertTrue(e.toString().toLowerCase().contains("not found"), - "Missing expected text in response: "+e.toString()); + Asserts.expectedFailureContainsIgnoreCase(e, "404", "not found"); } } } http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/036ba79a/usage/rest-server/src/main/java/org/apache/brooklyn/rest/resources/LocationResource.java ---------------------------------------------------------------------- diff --git a/usage/rest-server/src/main/java/org/apache/brooklyn/rest/resources/LocationResource.java b/usage/rest-server/src/main/java/org/apache/brooklyn/rest/resources/LocationResource.java index 9f865b3..5922ebd 100644 --- a/usage/rest-server/src/main/java/org/apache/brooklyn/rest/resources/LocationResource.java +++ b/usage/rest-server/src/main/java/org/apache/brooklyn/rest/resources/LocationResource.java @@ -27,15 +27,10 @@ import java.util.Set; import javax.ws.rs.core.Response; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.apache.brooklyn.api.catalog.CatalogItem; import org.apache.brooklyn.api.location.Location; import org.apache.brooklyn.api.location.LocationDefinition; import org.apache.brooklyn.api.typereg.RegisteredType; -import org.apache.brooklyn.core.catalog.internal.CatalogUtils; import org.apache.brooklyn.core.location.LocationConfigKeys; -import org.apache.brooklyn.core.typereg.RegisteredTypePredicates; import org.apache.brooklyn.rest.api.LocationApi; import org.apache.brooklyn.rest.domain.LocationSpec; import org.apache.brooklyn.rest.domain.LocationSummary; @@ -48,6 +43,8 @@ import org.apache.brooklyn.util.collections.MutableMap; import org.apache.brooklyn.util.exceptions.Exceptions; import org.apache.brooklyn.util.text.NaturalOrderComparator; import org.apache.brooklyn.util.text.Strings; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import com.google.common.base.Function; import com.google.common.base.Joiner; http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/036ba79a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/BrooklynRestApiLauncherTest.java ---------------------------------------------------------------------- diff --git a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/BrooklynRestApiLauncherTest.java b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/BrooklynRestApiLauncherTest.java index 50c7cb4..03f808d 100644 --- a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/BrooklynRestApiLauncherTest.java +++ b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/BrooklynRestApiLauncherTest.java @@ -24,14 +24,15 @@ import static org.apache.brooklyn.rest.BrooklynRestApiLauncher.StartMode.WEB_XML import java.util.concurrent.Callable; +import org.apache.brooklyn.rest.security.provider.AnyoneSecurityProvider; +import org.apache.brooklyn.rest.util.BrooklynRestResourceUtilsTest.SampleNoOpApplication; import org.apache.brooklyn.test.Asserts; -import org.apache.brooklyn.test.HttpTestUtils; +import org.apache.brooklyn.util.http.HttpAsserts; +import org.apache.brooklyn.util.http.HttpTool; import org.apache.http.HttpStatus; +import org.eclipse.jetty.server.NetworkConnector; import org.eclipse.jetty.server.Server; import org.testng.annotations.Test; -import org.apache.brooklyn.rest.security.provider.AnyoneSecurityProvider; -import org.apache.brooklyn.rest.util.BrooklynRestResourceUtilsTest.SampleNoOpApplication; -import org.eclipse.jetty.server.NetworkConnector; public class BrooklynRestApiLauncherTest extends BrooklynRestApiLauncherTestFixture { @@ -61,7 +62,7 @@ public class BrooklynRestApiLauncherTest extends BrooklynRestApiLauncherTestFixt int code = Asserts.succeedsEventually(new Callable<Integer>() { @Override public Integer call() throws Exception { - int code = HttpTestUtils.getHttpStatusCode(rootUrl+"/v1/catalog/applications"); + int code = HttpTool.getHttpStatusCode(rootUrl+"/v1/catalog/applications"); if (code == HttpStatus.SC_FORBIDDEN) { throw new RuntimeException("Retry request"); } else { @@ -69,8 +70,8 @@ public class BrooklynRestApiLauncherTest extends BrooklynRestApiLauncherTestFixt } } }); - HttpTestUtils.assertHealthyStatusCode(code); - HttpTestUtils.assertContentContainsText(rootUrl+"/v1/catalog/applications", SampleNoOpApplication.class.getSimpleName()); + HttpAsserts.assertHealthyStatusCode(code); + HttpAsserts.assertContentContainsText(rootUrl+"/v1/catalog/applications", SampleNoOpApplication.class.getSimpleName()); } } http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/036ba79a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/ApplicationResourceTest.java ---------------------------------------------------------------------- diff --git a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/ApplicationResourceTest.java b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/ApplicationResourceTest.java index 020fe19..738770d 100644 --- a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/ApplicationResourceTest.java +++ b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/ApplicationResourceTest.java @@ -67,9 +67,9 @@ import org.apache.brooklyn.rest.testing.mocks.RestMockApp; import org.apache.brooklyn.rest.testing.mocks.RestMockAppBuilder; import org.apache.brooklyn.rest.testing.mocks.RestMockSimpleEntity; import org.apache.brooklyn.test.Asserts; -import org.apache.brooklyn.test.HttpTestUtils; import org.apache.brooklyn.util.collections.CollectionFunctionals; import org.apache.brooklyn.util.exceptions.Exceptions; +import org.apache.brooklyn.util.http.HttpAsserts; import org.apache.brooklyn.util.time.Duration; import org.apache.http.HttpHeaders; import org.apache.http.entity.ContentType; @@ -158,7 +158,7 @@ public class ApplicationResourceTest extends BrooklynRestResourceTest { public void testDeployApplication() throws Exception { ClientResponse response = clientDeploy(simpleSpec); - HttpTestUtils.assertHealthyStatusCode(response.getStatus()); + HttpAsserts.assertHealthyStatusCode(response.getStatus()); assertEquals(getManagementContext().getApplications().size(), 1); assertRegexMatches(response.getLocation().getPath(), "/v1/applications/.*"); // Object taskO = response.getEntity(Object.class); @@ -619,7 +619,7 @@ public class ApplicationResourceTest extends BrooklynRestResourceTest { ClientResponse response = client().resource("/v1/applications") .entity(yaml, "application/x-yaml") .post(ClientResponse.class); - assertTrue(response.getStatus()/100 == 2, "response is "+response); + HttpAsserts.assertHealthyStatusCode(response.getStatus()); waitForPageFoundResponse("/v1/applications/my-app", ApplicationSummary.class); // Deprecate @@ -630,7 +630,7 @@ public class ApplicationResourceTest extends BrooklynRestResourceTest { ClientResponse response2 = client().resource("/v1/applications") .entity(yaml2, "application/x-yaml") .post(ClientResponse.class); - assertTrue(response2.getStatus()/100 == 2, "response is "+response2); + HttpAsserts.assertHealthyStatusCode(response2.getStatus()); waitForPageFoundResponse("/v1/applications/my-app2", ApplicationSummary.class); // Disable @@ -641,7 +641,7 @@ public class ApplicationResourceTest extends BrooklynRestResourceTest { ClientResponse response3 = client().resource("/v1/applications") .entity(yaml3, "application/x-yaml") .post(ClientResponse.class); - assertTrue(response3.getStatus()/100 == 4, "response is "+response3); + HttpAsserts.assertClientErrorStatusCode(response3.getStatus()); assertTrue(response3.getEntity(String.class).contains("cannot be matched")); waitForPageNotFoundResponse("/v1/applications/my-app3", ApplicationSummary.class); http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/036ba79a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/EntityResourceTest.java ---------------------------------------------------------------------- diff --git a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/EntityResourceTest.java b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/EntityResourceTest.java index 10d391a..d6857fb 100644 --- a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/EntityResourceTest.java +++ b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/EntityResourceTest.java @@ -35,9 +35,9 @@ import org.apache.brooklyn.rest.domain.EntitySpec; import org.apache.brooklyn.rest.domain.TaskSummary; import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest; import org.apache.brooklyn.rest.testing.mocks.RestMockSimpleEntity; -import org.apache.brooklyn.test.HttpTestUtils; import org.apache.brooklyn.util.collections.MutableList; import org.apache.brooklyn.util.exceptions.Exceptions; +import org.apache.brooklyn.util.http.HttpAsserts; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import org.slf4j.Logger; @@ -110,7 +110,7 @@ public class EntityResourceTest extends BrooklynRestResourceTest { .queryParam("name", "New Name") .post(ClientResponse.class); - HttpTestUtils.assertHealthyStatusCode(response.getStatus()); + HttpAsserts.assertHealthyStatusCode(response.getStatus()); Assert.assertTrue(entity.getDisplayName().equals("New Name")); } finally { // restore it for other tests! @@ -127,7 +127,7 @@ public class EntityResourceTest extends BrooklynRestResourceTest { .entity("services: [ { type: "+TestEntity.class.getName()+" }]", "application/yaml") .post(ClientResponse.class); - HttpTestUtils.assertHealthyStatusCode(response.getStatus()); + HttpAsserts.assertHealthyStatusCode(response.getStatus()); Assert.assertEquals(entity.getChildren().size(), 1); Entity child = Iterables.getOnlyElement(entity.getChildren()); Assert.assertTrue(Entities.isManaged(child)); @@ -152,7 +152,7 @@ public class EntityResourceTest extends BrooklynRestResourceTest { .get(ClientResponse.class); String raw = response.getEntity(String.class); log.info("TAGS raw: "+raw); - HttpTestUtils.assertHealthyStatusCode(response.getStatus()); + HttpAsserts.assertHealthyStatusCode(response.getStatus()); Assert.assertTrue(raw.contains(entity.getParent().getId()), "unexpected app tag, does not include ID: "+raw); http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/036ba79a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/SensorResourceTest.java ---------------------------------------------------------------------- diff --git a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/SensorResourceTest.java b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/SensorResourceTest.java index b3d49e5..4d2f781 100644 --- a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/SensorResourceTest.java +++ b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/SensorResourceTest.java @@ -36,8 +36,8 @@ import org.apache.brooklyn.rest.domain.EntitySpec; import org.apache.brooklyn.rest.test.config.render.TestRendererHints; import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest; import org.apache.brooklyn.rest.testing.mocks.RestMockSimpleEntity; -import org.apache.brooklyn.test.HttpTestUtils; import org.apache.brooklyn.util.collections.MutableMap; +import org.apache.brooklyn.util.http.HttpAsserts; import org.apache.brooklyn.util.stream.Streams; import org.apache.brooklyn.util.text.StringFunctions; import org.testng.annotations.AfterClass; @@ -156,7 +156,7 @@ public class SensorResourceTest extends BrooklynRestResourceTest { response = req.get(ClientResponse.class); } if (expectedValue!=null) { - HttpTestUtils.assertHealthyStatusCode(response.getStatus()); + HttpAsserts.assertHealthyStatusCode(response.getStatus()); Object value = response.getEntity(expectedValue.getClass()); assertEquals(value, expectedValue); } http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/036ba79a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/ServerShutdownTest.java ---------------------------------------------------------------------- diff --git a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/ServerShutdownTest.java b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/ServerShutdownTest.java index 6c8661f..dbe9afd 100644 --- a/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/ServerShutdownTest.java +++ b/usage/rest-server/src/test/java/org/apache/brooklyn/rest/resources/ServerShutdownTest.java @@ -31,6 +31,7 @@ import org.apache.brooklyn.api.entity.EntitySpec; import org.apache.brooklyn.api.mgmt.EntityManager; import org.apache.brooklyn.api.mgmt.Task; import org.apache.brooklyn.core.entity.Attributes; +import org.apache.brooklyn.core.entity.EntityAsserts; import org.apache.brooklyn.core.entity.drivers.BasicEntityDriverManager; import org.apache.brooklyn.core.entity.drivers.ReflectiveEntityDriverFactory; import org.apache.brooklyn.core.entity.lifecycle.Lifecycle; @@ -39,7 +40,6 @@ import org.apache.brooklyn.core.test.entity.TestApplication; import org.apache.brooklyn.rest.resources.ServerResourceTest.StopLatchEntity; import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest; import org.apache.brooklyn.test.Asserts; -import org.apache.brooklyn.test.EntityTestUtils; import org.apache.brooklyn.util.exceptions.Exceptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -116,7 +116,7 @@ public class ServerShutdownTest extends BrooklynRestResourceTest { EntitySpec<StopLatchEntity> latchEntitySpec = EntitySpec.create(StopLatchEntity.class); final StopLatchEntity entity = app.createAndManageChild(latchEntitySpec); app.start(ImmutableSet.of(app.newLocalhostProvisioningLocation())); - EntityTestUtils.assertAttributeEquals(entity, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING); + EntityAsserts.assertAttributeEquals(entity, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING); try { final Task<Void> firstStop = app.invoke(Startable.STOP, ImmutableMap.<String, Object>of()); http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/036ba79a/usage/test-support/src/main/java/org/apache/brooklyn/test/HttpTestUtils.java ---------------------------------------------------------------------- diff --git a/usage/test-support/src/main/java/org/apache/brooklyn/test/HttpTestUtils.java b/usage/test-support/src/main/java/org/apache/brooklyn/test/HttpTestUtils.java index 91a1f0e..ef19665 100644 --- a/usage/test-support/src/main/java/org/apache/brooklyn/test/HttpTestUtils.java +++ b/usage/test-support/src/main/java/org/apache/brooklyn/test/HttpTestUtils.java @@ -42,6 +42,7 @@ import javax.net.ssl.SSLSession; import org.apache.brooklyn.util.collections.MutableMap; import org.apache.brooklyn.util.crypto.SslTrustUtils; import org.apache.brooklyn.util.exceptions.Exceptions; +import org.apache.brooklyn.util.http.HttpTool; import org.apache.brooklyn.util.http.TrustingSslSocketFactory; import org.apache.brooklyn.util.stream.Streams; import org.apache.brooklyn.util.time.Time; @@ -59,14 +60,12 @@ import com.google.common.util.concurrent.ListeningExecutorService; * * @author aled * - * @deprecated since 0.9.0. Prefer org.apache.brooklyn.util.http.HttpAsserts which has no TestNG dependencies. + * @deprecated since 0.9.0. Prefer {@link org.apache.brooklyn.util.http.HttpAsserts} which has no TestNG dependencies + * (or {@link HttpTool} for some utility methods). */ @Deprecated public class HttpTestUtils { - // TODO Delete methods from TestUtils, to just have them here (or switch so TestUtils delegates here, - // and deprecate methods in TestUtils until deleted). - private static final Logger LOG = LoggerFactory.getLogger(HttpTestUtils.class); static final ExecutorService executor = Executors.newCachedThreadPool(); http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/036ba79a/utils/common/src/main/java/org/apache/brooklyn/test/Asserts.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/org/apache/brooklyn/test/Asserts.java b/utils/common/src/main/java/org/apache/brooklyn/test/Asserts.java index 678a181..668362a 100644 --- a/utils/common/src/main/java/org/apache/brooklyn/test/Asserts.java +++ b/utils/common/src/main/java/org/apache/brooklyn/test/Asserts.java @@ -33,8 +33,11 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; +import org.apache.brooklyn.util.collections.MutableList; import org.apache.brooklyn.util.collections.MutableSet; import org.apache.brooklyn.util.exceptions.Exceptions; +import org.apache.brooklyn.util.javalang.JavaClassNames; +import org.apache.brooklyn.util.text.StringPredicates; import org.apache.brooklyn.util.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -1034,6 +1037,135 @@ public class Asserts { fail("Failed "+condition+": "+object); } + public static void assertStringContains(String input, String phrase1ToContain, String ...optionalOtherPhrasesToContain) { + if (input==null) fail("Input is null."); + if (phrase1ToContain!=null) { + assertThat(input, StringPredicates.containsLiteral(phrase1ToContain)); + } + for (String otherPhrase: optionalOtherPhrasesToContain) { + if (otherPhrase!=null) { + assertThat(input, StringPredicates.containsLiteral(otherPhrase)); + } + } + } + + public static void assertStringContainsAtLeastOne(String input, String possiblePhrase1ToContain, String ...optionalOtherPossiblePhrasesToContain) { + if (input==null) fail("Input is null."); + List<String> missing = MutableList.of(); + if (possiblePhrase1ToContain!=null) { + if (input.contains(possiblePhrase1ToContain)) return; + missing.add(possiblePhrase1ToContain); + } + for (String otherPhrase: optionalOtherPossiblePhrasesToContain) { + if (otherPhrase!=null) { + if (input.contains(otherPhrase)) return; + missing.add(otherPhrase); + } + } + fail("Input did not contain any of the expected phrases "+missing+": "+input); + } + + public static void assertStringContainsIgnoreCase(String input, String phrase1ToContain, String ...optionalOtherPhrasesToContain) { + if (input==null) fail("Input is null."); + if (phrase1ToContain!=null) { + assertThat(input, StringPredicates.containsLiteralIgnoreCase(phrase1ToContain)); + } + for (String otherPhrase: optionalOtherPhrasesToContain) { + if (otherPhrase!=null) { + assertThat(input, StringPredicates.containsLiteralIgnoreCase(otherPhrase)); + } + } + } + + public static void assertStringMatchesRegex(String input, String regex1ToMatch, String ...optionalOtherRegexesToMatch) { + if (input==null) fail("Input is null."); + if (regex1ToMatch!=null) { + assertThat(input, StringPredicates.matchesRegex(regex1ToMatch)); + } + for (String otherRegex: optionalOtherRegexesToMatch) { + if (otherRegex!=null) { + assertThat(input, StringPredicates.matchesRegex(otherRegex)); + } + } + } + + /** Subclass of {@link AssertionError} which indicates that code which should have thrown did not, + * so that callers can disambiguate expected errors from this one. + * See {@link #shouldHaveFailedPreviously()} */ + public static class ShouldHaveFailedPreviouslyAssertionError extends AssertionError { + private static final long serialVersionUID = 4359541529633617518L; + public ShouldHaveFailedPreviouslyAssertionError() { this("Should have failed previously."); } + public ShouldHaveFailedPreviouslyAssertionError(String message) { super(message); } + } + + /** Throws a {@link ShouldHaveFailedPreviouslyAssertionError} exception, + * to more easily distinguish this failure from other fails. + * In particular, use one of the <code>expectedFailure</code> methods + * in the surrounding <code>catch</code> block and this error will pass through it. */ + public static void shouldHaveFailedPreviously() { + throw new ShouldHaveFailedPreviouslyAssertionError(); + } + /** As {@link #shouldHaveFailedPreviously()} but allowing detail, + * for example a value which was received when it shouldn't have been. */ + public static void shouldHaveFailedPreviously(String message) { + throw new ShouldHaveFailedPreviouslyAssertionError(message); + } + + /** Tests that an exception is not {@link ShouldHaveFailedPreviouslyAssertionError}. + * See {@link #shouldHaveFailedPreviously()} */ + public static void expectedFailure(Throwable e) { + if (e instanceof ShouldHaveFailedPreviouslyAssertionError) throw (Error)e; + } + + /** Tests that an exception is not {@link ShouldHaveFailedPreviouslyAssertionError} + * and is one of the given types. + * + * @return If the test is satisfied, this method returns normally. + * The caller can decide whether anything more should be done with the exception. + * If the test fails, then either it is propagated, + * if the {@link Throwable} is a fatal ({@link Exceptions#propagateIfFatal(Throwable)}) other than an {@link AssertionError}, + * or more usually the test failure of this method is thrown, + * with detail of the original {@link Throwable} logged. */ + public static void expectedFailureOfType(Throwable e, Class<?> ...permittedSupertypes) { + if (e instanceof ShouldHaveFailedPreviouslyAssertionError) throw (Error)e; + for (Class<?> t: permittedSupertypes) { + if (t.isInstance(e)) return; + } + rethrowPreferredException(e, + new AssertionError("Error "+JavaClassNames.simpleClassName(e)+" is not any of the expected types: " + Arrays.asList(permittedSupertypes))); + } + + /** Tests {@link #expectedFailure(Throwable)} and that the <code>toString</code> + * satisfies {@link #assertStringContains(String, String, String...)}. + * @return as per {@link #expectedFailureOfType(Throwable, Class...)} */ + public static void expectedFailureContains(Throwable e, String phrase1ToContain, String ...optionalOtherPhrasesToContain) { + if (e instanceof ShouldHaveFailedPreviouslyAssertionError) throw (Error)e; + try { + assertStringContains(e.toString(), phrase1ToContain, optionalOtherPhrasesToContain); + } catch (AssertionError ee) { + rethrowPreferredException(e, ee); + } + } + + /** As {@link #expectedFailureContains(Throwable, String, String...)} but case insensitive */ + public static void expectedFailureContainsIgnoreCase(Throwable e, String phrase1ToContain, String ...optionalOtherPhrasesToContain) { + if (e instanceof ShouldHaveFailedPreviouslyAssertionError) throw (Error)e; + try { + assertStringContainsIgnoreCase(e.toString(), phrase1ToContain, optionalOtherPhrasesToContain); + } catch (AssertionError ee) { + rethrowPreferredException(e, ee); + } + } + + /** Implements the return beahvior for {@link #expectedFailureOfType(Throwable, Class...)} and others. */ + private static void rethrowPreferredException(Throwable earlierPreferredIfFatalElseLogged, Throwable laterPreferredOtherwise) throws AssertionError { + if (!(earlierPreferredIfFatalElseLogged instanceof AssertionError)) { + Exceptions.propagateIfFatal(earlierPreferredIfFatalElseLogged); + } + log.warn("Detail of unexpected error: "+earlierPreferredIfFatalElseLogged, earlierPreferredIfFatalElseLogged); + throw Exceptions.propagate(laterPreferredOtherwise); + } + @SuppressWarnings("rawtypes") private static boolean groovyTruth(Object o) { // TODO Doesn't handle matchers (see http://docs.codehaus.org/display/GROOVY/Groovy+Truth) @@ -1102,4 +1234,5 @@ public class Asserts { if (t instanceof Error) throw (Error)t; throw new RuntimeException(t); } + } http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/036ba79a/utils/common/src/main/java/org/apache/brooklyn/util/http/HttpAsserts.java ---------------------------------------------------------------------- diff --git a/utils/common/src/main/java/org/apache/brooklyn/util/http/HttpAsserts.java b/utils/common/src/main/java/org/apache/brooklyn/util/http/HttpAsserts.java index 3a8c9ca..a7c195f 100644 --- a/utils/common/src/main/java/org/apache/brooklyn/util/http/HttpAsserts.java +++ b/utils/common/src/main/java/org/apache/brooklyn/util/http/HttpAsserts.java @@ -40,21 +40,46 @@ import com.google.common.util.concurrent.ListeningExecutorService; */ public class HttpAsserts { - // TODO Delete methods from TestUtils, to just have them here (or switch so TestUtils delegates here, - // and deprecate methods in TestUtils until deleted). - private static final Logger LOG = LoggerFactory.getLogger(HttpAsserts.class); - /** - * Assert that a 'successful' (2xx) status code has been provided. - * - * @param code The status code. - */ + /** @return whether the given HTTP status code is a "success" class code (2xx) */ + public static boolean isHealthyStatusCode(int code) { + return code>=200 && code<=299; + } + + /** Asserts that the given HTTP status code indicates "success", i.e. {@link #isHealthyStatusCode(int)} is true */ public static void assertHealthyStatusCode(int code) { - if (code>=200 && code<=299) return; - Asserts.fail("Wrong status code: " + code); + if (isHealthyStatusCode(code)) return; + Asserts.fail("Expected success status code, got: " + code); + } + + /** Asserts that the given HTTP status code does not indicate "success", i.e. {@link #isHealthyStatusCode(int)} returns false */ + public static void assertNotHealthyStatusCode(int code) { + if (!isHealthyStatusCode(code)) return; + Asserts.fail("Expected non-success status code, got: " + code); + } + + /** @return whether the given HTTP status code is a "client error" class code (4xx) */ + public static boolean isClientErrorStatusCode(int code) { + return code>=400 && code<=499; + } + + /** Asserts that the given HTTP status code indicates "client error", i.e. {@link #isClientErrorStatusCode(int)} is true */ + public static void assertClientErrorStatusCode(int code) { + if (isClientErrorStatusCode(code)) return; + Asserts.fail("Expected client error status code, got: " + code); + } + + /** @return whether the given HTTP status code is a "server error" class code (5xx) */ + public static boolean isServerErrorStatusCode(int code) { + return code>=500 && code<=599; } + /** Asserts that the given HTTP status code indicates "server error", i.e. {@link #isServerErrorStatusCode(int)} is true */ + public static void assertServerErrorStatusCode(int code) { + if (isServerErrorStatusCode(code)) return; + Asserts.fail("Expected server error status code, got: " + code); + } /** * Asserts that gets back any "valid" response - i.e. not an exception. This could be an unauthorized, @@ -312,6 +337,5 @@ public class HttpAsserts { } }); } - } http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/036ba79a/utils/common/src/test/java/org/apache/brooklyn/test/AssertsTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/test/AssertsTest.java b/utils/common/src/test/java/org/apache/brooklyn/test/AssertsTest.java index d72be76..d770c43 100644 --- a/utils/common/src/test/java/org/apache/brooklyn/test/AssertsTest.java +++ b/utils/common/src/test/java/org/apache/brooklyn/test/AssertsTest.java @@ -18,12 +18,14 @@ */ package org.apache.brooklyn.test; +import java.util.NoSuchElementException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.brooklyn.test.Asserts; +import org.apache.brooklyn.test.Asserts.ShouldHaveFailedPreviouslyAssertionError; import org.apache.brooklyn.util.collections.MutableMap; import org.apache.brooklyn.util.exceptions.Exceptions; import org.apache.brooklyn.util.time.Duration; @@ -92,4 +94,76 @@ public class AssertsTest { if (ise == null || !ise.toString().contains("Simulating failure")) throw e; } } + + @Test + public void testAssertStrings() { + Asserts.assertStringContains("hello", "hello", "he"); + try { + Asserts.assertStringContains("hello", "goodbye"); + Asserts.shouldHaveFailedPreviously(); + } catch (AssertionError e) { + Asserts.expectedFailureContains(e, "hello", "goodbye"); + Asserts.expectedFailureContainsIgnoreCase(e, "hello", "Goodbye"); + } + + Asserts.assertStringContainsIgnoreCase("hello", "Hello"); + try { + Asserts.assertStringContains("hello", "Hello"); + Asserts.shouldHaveFailedPreviously(); + } catch (AssertionError e) { Asserts.expectedFailureContains(e, "hello", "Hello"); } + + Asserts.assertStringContainsAtLeastOne("hello", "hello", "goodbye"); + try { + Asserts.assertStringContainsAtLeastOne("hello", "Hello", "goodbye"); + Asserts.shouldHaveFailedPreviously(); + } catch (AssertionError e) { Asserts.expectedFailureContains(e, "hello", "Hello", "goodbye"); } + + Asserts.assertStringMatchesRegex("hello", "hello", "he.*", "he[ckl]+e*o"); + try { + Asserts.assertStringMatchesRegex("hello", "hello", "he"); + Asserts.shouldHaveFailedPreviously(); + } catch (AssertionError e) { Asserts.expectedFailureContains(e, "hello", "matchesRegex(he)"); } + } + + @Test + public void testExpectedFailures() { + Asserts.expectedFailureOfType(new IllegalStateException(), + NoSuchElementException.class, IllegalStateException.class); + Asserts.expectedFailureOfType(new IllegalStateException(), + NoSuchElementException.class, Object.class); + + try { + Asserts.expectedFailureOfType(new IllegalStateException(), + NoSuchElementException.class, Error.class); + Asserts.shouldHaveFailedPreviously(); + } catch (Throwable e) { Asserts.expectedFailure(e); } + } + + @Test + public void testShouldHaveFailed() { + int reached = 0; + try { + try { + // in normal tests the following indicates that an expected failure didn't happen + // (but here we are testing it) + Asserts.shouldHaveFailedPreviously(); + reached--; + } catch (Throwable e) { + // in normal tests the following indicates that a failure was NOT thrown by the above + // (but here the call *below* should rethrow) + reached++; + Asserts.expectedFailure(e); + reached--; + } + reached--; + throw new AssertionError("It should have failed previously, with a " + + "ShouldHaveFailedPreviouslyAssertionError in the first block rethrown by the second"); + } catch (ShouldHaveFailedPreviouslyAssertionError e) { + // expected + reached++; + } + reached++; + // check code flowed the way we expected + Asserts.assertEquals(reached, 3); + } }
