diff --git a/pom.xml b/pom.xml index d28dd21a5..a9e148278 100644 --- a/pom.xml +++ b/pom.xml @@ -43,16 +43,17 @@ src/test/munit ${basedir}/target/test-mule/munit - 1.1.2 - 2.3.0 - 2.3.0 + 1.2.0-SNAPSHOT + 3.1.0-SNAPSHOT + 3.1.0-SNAPSHOT 3.0.2 5.8.0 - 0.8.6 + 0.8.10 2.13.5 2.3.4 2.10.0 4.13.2 + 4.11.0 @@ -369,6 +370,13 @@ 1.4.01 test + + + org.mockito + mockito-junit-jupiter + ${mockito-junit-jupiter.version} + test + diff --git a/src/test/java/org/mule/module/apikit/ExtensionDeclarerTestCase.java b/src/test/java/org/mule/module/apikit/ExtensionDeclarerTestCase.java deleted file mode 100644 index d2bfcd3f2..000000000 --- a/src/test/java/org/mule/module/apikit/ExtensionDeclarerTestCase.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com - * The software in this package is published under the terms of the CPAL v1.0 - * license, a copy of which has been included with this distribution in the - * LICENSE.txt file. - */ -package org.mule.module.apikit; - -import static java.util.Collections.emptySet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import org.mule.runtime.api.dsl.DslResolvingContext; -import org.mule.runtime.api.meta.model.ExtensionModel; -import org.mule.runtime.api.meta.model.declaration.fluent.ExtensionDeclarer; -import org.mule.runtime.extension.api.loader.ExtensionLoadingContext; -import org.mule.runtime.extension.api.persistence.ExtensionModelJsonSerializer; -import org.mule.runtime.extension.internal.loader.DefaultExtensionLoadingContext; -import org.mule.runtime.extension.internal.loader.ExtensionModelFactory; - -import org.junit.Test; - -public class ExtensionDeclarerTestCase { - - @Test - public void getApikitExtensionDeclarer() { - ApikitExtensionLoadingDelegate apikitExtensionLoadingDelegate = new ApikitExtensionLoadingDelegate(); - ExtensionDeclarer extensionDeclarer = new ExtensionDeclarer(); - apikitExtensionLoadingDelegate.accept(extensionDeclarer, null); - ExtensionModelJsonSerializer serializer = new ExtensionModelJsonSerializer(true); - ExtensionLoadingContext ctx = - new DefaultExtensionLoadingContext(extensionDeclarer, Thread.currentThread().getContextClassLoader(), - DslResolvingContext.getDefault(emptySet())); - ExtensionModel extensionModel = new ExtensionModelFactory().create(ctx); - String jsonContent = serializer.serialize(extensionModel); - assertNotNull(jsonContent); - assertEquals(2, countOccurences(jsonContent, "BAD_REQUEST")); - assertEquals(3, countOccurences(jsonContent, "NOT_FOUND")); - assertEquals(2, countOccurences(jsonContent, "METHOD_NOT_ALLOWED")); - assertEquals(2, countOccurences(jsonContent, "UNSUPPORTED_MEDIA_TYPE")); - assertEquals(2, countOccurences(jsonContent, "NOT_ACCEPTABLE")); - } - - private static int countOccurences(String str, String substring) { - int lastIndex = 0; - int count = 0; - while (lastIndex >= 0) { - lastIndex = str.indexOf(substring, lastIndex); - if (lastIndex >= 0) { - count++; - lastIndex += substring.length(); - } - } - return count; - } -} diff --git a/src/test/java/org/mule/module/apikit/MockingUtils.java b/src/test/java/org/mule/module/apikit/MockingUtils.java deleted file mode 100644 index 0d2e299cd..000000000 --- a/src/test/java/org/mule/module/apikit/MockingUtils.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com - * The software in this package is published under the terms of the CPAL v1.0 - * license, a copy of which has been included with this distribution in the - * LICENSE.txt file. - */ -package org.mule.module.apikit; - -import sun.reflect.ConstructorAccessor; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; - -public class MockingUtils { - - public static T createEnumValue(Class enumClass, String name, int ordinal, String description) throws Exception { - Class monsterClass = enumClass; - Constructor constructor = monsterClass.getDeclaredConstructors()[0]; - constructor.setAccessible(true); - - Field constructorAccessorField = Constructor.class.getDeclaredField("constructorAccessor"); - constructorAccessorField.setAccessible(true); - ConstructorAccessor ca = (ConstructorAccessor) constructorAccessorField.get(constructor); - if (ca == null) { - Method acquireConstructorAccessorMethod = Constructor.class.getDeclaredMethod("acquireConstructorAccessor"); - acquireConstructorAccessorMethod.setAccessible(true); - ca = (ConstructorAccessor) acquireConstructorAccessorMethod.invoke(constructor); - } - T enumValue = - (T) ca.newInstance(description != null ? new Object[] {name, ordinal, description} : new Object[] {name, ordinal}); - return enumValue; - } - - public static void setAccessible(Field field, Object newValue) throws Exception { - field.setAccessible(true); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - field.set(null, newValue); - } -} diff --git a/src/test/java/org/mule/module/apikit/MuleVersionUtilsTest.java b/src/test/java/org/mule/module/apikit/MuleVersionUtilsTest.java deleted file mode 100644 index 30e280907..000000000 --- a/src/test/java/org/mule/module/apikit/MuleVersionUtilsTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com - * The software in this package is published under the terms of the CPAL v1.0 - * license, a copy of which has been included with this distribution in the - * LICENSE.txt file. - */ -package org.mule.module.apikit; - -import org.junit.Test; -import org.mule.module.apikit.utils.MuleVersionUtils; -import org.mule.runtime.core.api.config.MuleManifest; - -import java.util.jar.Attributes; -import java.util.jar.Manifest; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.mule.module.apikit.MockingUtils.setAccessible; - -public class MuleVersionUtilsTest { - - @Test - public void newerVersionIsAtLeastTest() throws Exception { - setManifestImplementationVersion("4.3.0"); - assertTrue(MuleVersionUtils.isAtLeast("4.2.0")); - } - - @Test - public void newerSnapshotVersionIsAtLeastTest() throws Exception { - setManifestImplementationVersion("4.3.0-SNAPSHOT"); - assertTrue(MuleVersionUtils.isAtLeast("4.2.0")); - } - - @Test - public void olderVersionIsAtLeastTest() throws Exception { - setManifestImplementationVersion("4.1.0"); - assertFalse(MuleVersionUtils.isAtLeast("4.2.0")); - } - - @Test - public void olderSnapshotVersionIsAtLeastTest() throws Exception { - setManifestImplementationVersion("4.1.0-SNAPSHOT"); - assertFalse(MuleVersionUtils.isAtLeast("4.2.0")); - } - - @Test - public void sameVersionIsAtLeastTest() throws Exception { - setManifestImplementationVersion("4.2.0"); - assertTrue(MuleVersionUtils.isAtLeast("4.2.0")); - } - - @Test - public void snapshotVersionIsAtLeastTest() throws Exception { - setManifestImplementationVersion("4.2.0-SNAPSHOT"); - assertTrue(MuleVersionUtils.isAtLeast("4.2.0")); - } - - @Test - public void hotFixVersionIsAtLeastTest() throws Exception { - setManifestImplementationVersion("4.2.0-hf1"); - assertTrue(MuleVersionUtils.isAtLeast("4.2.0")); - } - - @Test - public void hotFixWithDateSuffixVersionIsAtLeastTest() throws Exception { - setManifestImplementationVersion("4.2.0-20200525"); - assertTrue(MuleVersionUtils.isAtLeast("4.2.0")); - } - - @Test - public void releaseCandidateVersionIsAtLeastTest() throws Exception { - setManifestImplementationVersion("4.2.0-rc1"); - assertTrue(MuleVersionUtils.isAtLeast("4.2.0")); - } - - @Test - public void invalidVersionIsAtLeastTest() throws Exception { - setManifestImplementationVersion("4.2.0"); - assertFalse(MuleVersionUtils.isAtLeast("a.b.3")); - } - - @Test - public void blankVersionIsAtLeastTest() throws Exception { - setManifestImplementationVersion("4.2.0"); - assertFalse(MuleVersionUtils.isAtLeast(" ")); - } - - @Test - public void nullVersionIsAtLeastTest() throws Exception { - setManifestImplementationVersion("4.2.0"); - assertFalse(MuleVersionUtils.isAtLeast(null)); - } - - private void setManifestImplementationVersion(String version) throws Exception { - Manifest manifestMock = mock(Manifest.class); - when(manifestMock.getMainAttributes()).thenReturn(mock(Attributes.class)); - when(manifestMock.getMainAttributes().getValue(new Attributes.Name("Implementation-Version"))).thenReturn(version); - setAccessible(MuleManifest.class.getDeclaredField("manifest"), manifestMock); - } - - -} diff --git a/src/test/java/org/mule/module/apikit/RamlHandlerTestCase.java b/src/test/java/org/mule/module/apikit/RamlHandlerTestCase.java deleted file mode 100644 index 1295ce271..000000000 --- a/src/test/java/org/mule/module/apikit/RamlHandlerTestCase.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com - * The software in this package is published under the terms of the CPAL v1.0 - * license, a copy of which has been included with this distribution in the - * LICENSE.txt file. - */ -package org.mule.module.apikit; - -import org.apache.commons.io.IOUtils; -import org.junit.BeforeClass; -import org.junit.Test; -import org.mule.apikit.model.ApiSpecification; -import org.mule.apikit.model.ApiVendor; -import org.mule.module.apikit.api.RamlHandler; -import org.mule.parser.service.ParserMode; -import org.mule.parser.service.result.DefaultParsingIssue; -import org.mule.parser.service.result.ParsingIssue; -import org.mule.parser.service.result.UnsupportedParsingIssue; -import org.mule.runtime.core.api.MuleContext; - -import java.io.IOException; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.List; -import java.util.function.Supplier; -import java.util.stream.Stream; - -import static java.util.stream.Collectors.toList; -import static junit.framework.TestCase.assertTrue; -import static junit.framework.TestCase.fail; -import static org.hamcrest.core.StringContains.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.mule.apikit.ApiType.AMF; -import static org.mule.apikit.ApiType.RAML; -import static org.mule.parser.service.ParserMode.AUTO; - -public class RamlHandlerTestCase { - - private static final String UNSUPPORTED_FEATURE_CAUSE = "Unsupported Feature Cause"; - private static final String TEST_CAUSE = "Test Cause"; - private static MuleContext muleContext; - - @BeforeClass - public static void beforeAll() { - muleContext = mock(MuleContext.class); - when(muleContext.getExecutionClassLoader()).thenReturn(Thread.currentThread().getContextClassLoader()); - } - - @Test - public void apiVendorForRaml08() { - String ramlLocation = "unit/raml-handler/simple08.raml"; - String apiServer = "unused"; - RamlHandler handler = createRamlHandler(ramlLocation, true); - handler.setApiServer(apiServer); - assertTrue(handler.getApiVendor().equals(ApiVendor.RAML_08)); - } - - @Test - public void isParserV2TrueUsingRaml10() { - String ramlLocation = "unit/raml-handler/simple10.raml"; - String apiServer = "unused"; - RamlHandler handler = createRamlHandler(ramlLocation); - handler.setApiServer(apiServer); - assertTrue(handler.isParserV2()); - assertTrue(handler.getApiVendor().equals(ApiVendor.RAML_10)); - } - - @Test - public void addLocalHostAsServerWhenIsNotDefined() { - String ramlLocation = "unit/raml-handler/simple10.raml"; - boolean keepRamlBaseUri = false; - RamlHandler handler = createRamlHandler(ramlLocation, keepRamlBaseUri); - handler.setApiServer("localhost:8081/"); - String rootRaml = handler.getAMFModel(); - assertThat(rootRaml, containsString("localhost:8081/")); - } - - @Test - public void streamAMFModelReplacingUrl() throws IOException { - RamlHandler handler = createRamlHandler("unit/raml-handler/simple10.raml", false); - PipedOutputStream pipedOutputStream = new PipedOutputStream(); - PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream); - Thread thread = new Thread(() -> handler.writeAMFModel("http://google.com", pipedOutputStream)); - thread.start(); - String model = IOUtils.toString(pipedInputStream); - assertThat(model, containsString("http://google.com")); - } - - @Test - public void getRamlV2KeepRamlBaseUriTrue() { - String ramlLocation = "unit/raml-handler/simple10-with-example.raml"; - boolean keepRamlBaseUri = true; - String apiServer = "http://www.newBaseUri.com"; - RamlHandler handler = createRamlHandler(ramlLocation, keepRamlBaseUri); - handler.setApiServer(apiServer); - String rootRaml = handler.getRamlV2("unit/raml-handler/?raml"); - assertTrue(rootRaml.contains("RAML 1.0")); - assertTrue(!rootRaml.contains(apiServer)); - assertTrue(rootRaml.contains("baseUri: http://localhost/myapi")); - } - - - - @Test - public void getRamlV2KeepRamlBaseUriFalse() { - String ramlLocation = "unit/raml-handler/simple10-with-example.raml";// this.getClass().getResource("../../../../org/mule/module/apikit/simple-raml/simple10-with-example.raml").toString(); - String apiServer = "http://pepe.com"; - RamlHandler handler = createRamlHandler(ramlLocation, false); - handler.setApiServer(apiServer); - - String ramlV1 = handler.getRamlV1(); - assertTrue(ramlV1.contains("baseUri: " + apiServer)); - - String ramlV2 = handler.getRamlV2("unit/raml-handler/?raml"); - assertTrue(ramlV2.contains("baseUri: " + apiServer)); - - String ramlAmf = handler.getAMFModel(); - assertThat(ramlAmf, containsString("\"" + apiServer + "\"")); - } - - @Test - public void getRamlV2Example() { - String ramlLocation = "unit/raml-handler/simple10-with-example.raml"; - String apiServer = "unused"; - RamlHandler handler = createRamlHandler(ramlLocation); - handler.setApiServer(apiServer); - assertTrue(handler.getRamlV2("unit/raml-handler/example.json/?raml").contains("{\"name\":\"jane\"}")); - } - - @Test - public void testInitializationUsingAUTO() { - RamlHandler handler; - - final boolean keepRamlBaseUri = true; - - handler = createRamlHandler("unit/raml-handler/amf-only.raml", keepRamlBaseUri, ParserMode.AUTO); - assertEquals(AMF, handler.getApi().getType()); - - assertException("Invalid reference 'SomeTypo'", - () -> createRamlHandler("unit/raml-handler/failing-api.raml", keepRamlBaseUri, ParserMode.AUTO)); - } - - @Test - public void testInitializationUsingAMF() { - RamlHandler handler; - - final boolean keepRamlBaseUri = true; - - handler = createRamlHandler("unit/raml-handler/amf-only.raml", keepRamlBaseUri, ParserMode.AMF); - assertEquals(AMF, handler.getApi().getType()); - - assertException("Unresolved reference 'SomeTypo'", - () -> createRamlHandler("unit/raml-handler/failing-api.raml", keepRamlBaseUri, ParserMode.AMF)); - } - - @Test - public void testInitializationUsingRAML() { - RamlHandler handler; - - final boolean keepRamlBaseUri = true; - - handler = createRamlHandler("unit/raml-handler/raml-parser-only.raml", keepRamlBaseUri, ParserMode.RAML); - assertEquals(RAML, handler.getApi().getType()); - - assertException("Invalid reference 'SomeTypo'", - () -> createRamlHandler("unit/raml-handler/failing-api.raml", keepRamlBaseUri, ParserMode.RAML)); - } - - @Test - public void ramlWithSpacesInPath() { - RamlHandler handler = createRamlHandler("unit/space in path api/api.raml", true, ParserMode.RAML); - ApiSpecification api = handler.getApi(); - assertEquals(RAML, api.getType()); - List refs = api.getAllReferences(); - assertTrue(refs.stream().anyMatch(ref -> ref.endsWith("unit/space%20in%20path%20api/example.json"))); - assertTrue(refs.stream().anyMatch(ref -> ref.endsWith("unit/space%20in%20path%20api/more%20spaces/schema.json"))); - } - - @Test - public void oas30WithUnsupportedFeatures() { - assertNotNull(createRamlHandler("unit/raml-handler/oas30-api.yaml", true, ParserMode.AMF)); - } - - @Test - public void testFilteringOutUnsupportedParsingIssue() throws Exception { - RamlHandler ramlHandler = mock(RamlHandler.class); - Class[] cArg = new Class[2]; - cArg[0] = List.class; - cArg[1] = boolean.class; - Method getFilteredParsingIssueStream = RamlHandler.class.getDeclaredMethod("getFilteredParsingIssueStream", cArg); - getFilteredParsingIssueStream.setAccessible(true); - List parsingIssues = - Arrays.asList(new DefaultParsingIssue(TEST_CAUSE), new UnsupportedParsingIssue(UNSUPPORTED_FEATURE_CAUSE)); - Stream result = (Stream) getFilteredParsingIssueStream.invoke(ramlHandler, parsingIssues, true); - List collectedResults = result.map(e -> e.cause()).collect(toList()); - assertEquals(1, collectedResults.size()); - assertEquals(TEST_CAUSE, collectedResults.get(0)); - result = (Stream) getFilteredParsingIssueStream.invoke(ramlHandler, parsingIssues, false); - collectedResults = result.map(e -> e.cause()).collect(toList()); - assertEquals(2, collectedResults.size()); - assertEquals(TEST_CAUSE, collectedResults.get(0)); - assertEquals(UNSUPPORTED_FEATURE_CAUSE, collectedResults.get(1)); - } - - private void assertException(String message, Supplier supplier) { - try { - supplier.get(); - fail("an exception was expected"); - } catch (Exception e) { - assertThat(e.getMessage(), containsString(message)); - } - } - - private RamlHandler createRamlHandler(String ramlPath) { - return createRamlHandler(ramlPath, true, AUTO); - } - - private RamlHandler createRamlHandler(String ramlPath, boolean keepRamlBaseUri) { - return createRamlHandler(ramlPath, keepRamlBaseUri, AUTO); - } - - private RamlHandler createRamlHandler(String ramlPath, boolean keepRamlBaseUri, ParserMode parser) { - return createRamlHandler(ramlPath, keepRamlBaseUri, parser, false); - } - - private RamlHandler createRamlHandler(String ramlPath, boolean keepRamlBaseUri, ParserMode parser, - boolean filterUnsupportedLogging) { - try { - return new RamlHandler(null, ramlPath, keepRamlBaseUri, muleContext.getErrorTypeRepository(), parser, - filterUnsupportedLogging); - } catch (IOException e) { - throw new RuntimeException("Error creating RamlHandler", e); - } - } -} diff --git a/src/test/java/org/mule/module/apikit/RoutingTableTestCase.java b/src/test/java/org/mule/module/apikit/RoutingTableTestCase.java deleted file mode 100644 index 432936175..000000000 --- a/src/test/java/org/mule/module/apikit/RoutingTableTestCase.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com - * The software in this package is published under the terms of the CPAL v1.0 - * license, a copy of which has been included with this distribution in the - * LICENSE.txt file. - */ -package org.mule.module.apikit; - -import static org.hamcrest.CoreMatchers.hasItems; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.IOException; - -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.mule.module.apikit.api.RamlHandler; -import org.mule.module.apikit.api.RoutingTable; -import org.mule.module.apikit.api.uri.URIPattern; -import org.mule.module.apikit.api.uri.URIResolver; -import org.mule.module.apikit.uri.URIResolveResult; -import org.mule.runtime.core.api.MuleContext; - -public class RoutingTableTestCase { - - private static RamlHandler ramlHandler; - private static MuleContext muleContext; - - @BeforeClass - public static void beforeAll() throws IOException { - muleContext = mock(MuleContext.class); - when(muleContext.getExecutionClassLoader()).thenReturn(Thread.currentThread().getContextClassLoader()); - ramlHandler = new RamlHandler("unit/routing-table-sample.raml", true, muleContext.getErrorTypeRepository()); - } - - public RoutingTableTestCase() {} - - @Test - public void testResourceFlattenedTree() { - RoutingTable routingTable = new RoutingTable(ramlHandler.getApi()); - - Assert.assertThat(routingTable.keySet(), hasItems(new URIPattern("/single-resource"), - new URIPattern("/api"), - new URIPattern("/api/sub-resource"), - new URIPattern("/api/sub-resource-types"))); - } - - @Test - public void emptyParametersAreMatchedButNotResolved() { - URIPattern pattern = new URIPattern("/api/{parameter}/list"); - Assert.assertTrue(pattern.match("/api//list")); - URIResolver resolver = new URIResolver("/api//list"); - Assert.assertEquals(URIResolveResult.Status.ERROR, resolver.resolve(pattern).getStatus()); - } - - @Test - public void getResourceByPattern() { - RoutingTable routingTable = new RoutingTable(ramlHandler.getApi()); - - Assert.assertNotNull(routingTable.getResource(new URIPattern("/single-resource"))); - Assert.assertNotNull(routingTable.getResource(new URIPattern("/api/sub-resource"))); - } - - @Test - public void getResourceByString() { - RoutingTable routingTable = new RoutingTable(ramlHandler.getApi()); - - Assert.assertNotNull(routingTable.getResource("/single-resource")); - Assert.assertNotNull(routingTable.getResource("/api/sub-resource")); - } -} diff --git a/src/test/java/org/mule/module/apikit/console/BaseUriReplacementTestCase.java b/src/test/java/org/mule/module/apikit/console/BaseUriReplacementTestCase.java deleted file mode 100644 index 6217c796c..000000000 --- a/src/test/java/org/mule/module/apikit/console/BaseUriReplacementTestCase.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com - * The software in this package is published under the terms of the CPAL v1.0 - * license, a copy of which has been included with this distribution in the - * LICENSE.txt file. - */ -package org.mule.module.apikit.console; - -import org.junit.After; -import org.junit.BeforeClass; -import org.junit.Test; -import org.mule.module.apikit.api.RamlHandler; -import org.mule.module.apikit.api.UrlUtils; -import org.mule.runtime.api.exception.ErrorTypeRepository; -import org.mule.runtime.core.api.MuleContext; - -import static java.lang.System.clearProperty; -import static java.lang.System.setProperty; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.mule.module.apikit.api.UrlUtils.getBaseUriReplacement; -import static org.mule.module.apikit.api.UrlUtils.replaceHostInURL; -import static org.mule.parser.service.ParserMode.AUTO; - -public class BaseUriReplacementTestCase { - - private static final String FULL_DOMAIN = UrlUtils.FULL_DOMAIN; - - private static MuleContext muleContext; - - @BeforeClass - public static void beforeAll() { - muleContext = mock(MuleContext.class); - when(muleContext.getExecutionClassLoader()).thenReturn(Thread.currentThread().getContextClassLoader()); - } - - @Test - public void baseUriReplacementTest() throws Exception { - ErrorTypeRepository errorRepo = muleContext.getErrorTypeRepository(); - RamlHandler ramlHandler = new RamlHandler(null, "unit/console/simple-with-baseuri10.raml", false, errorRepo, AUTO); - assertEquals("http://localhost:8081/api", ramlHandler.getBaseUriReplacement("http://localhost:8081/api")); - assertEquals("http://localhost:8081/api", ramlHandler.getBaseUriReplacement("http://0.0.0.0:8081/api")); - - setProperty(FULL_DOMAIN, "pepe.cloudhub.io"); - assertEquals("http://localhost:8081/api", ramlHandler.getBaseUriReplacement("http://localhost:8081/api")); - assertEquals("http://pepe.cloudhub.io/api", ramlHandler.getBaseUriReplacement("http://0.0.0.0:8081/api")); - - setProperty(FULL_DOMAIN, "http://pepe.cloudhub.io"); - assertEquals("http://localhost:8081/api", ramlHandler.getBaseUriReplacement("http://localhost:8081/api")); - assertEquals("http://pepe.cloudhub.io/api", ramlHandler.getBaseUriReplacement("http://0.0.0.0:8081/api")); - - setProperty(FULL_DOMAIN, "http://pepe.cloudhub.io/"); - assertEquals("http://localhost:8081/api", ramlHandler.getBaseUriReplacement("http://localhost:8081/api")); - assertEquals("http://pepe.cloudhub.io/api", ramlHandler.getBaseUriReplacement("http://0.0.0.0:8081/api")); - - setProperty(FULL_DOMAIN, "pepe.cloudhub.io/"); - assertEquals("http://localhost:8081/api", ramlHandler.getBaseUriReplacement("http://localhost:8081/api")); - assertEquals("http://pepe.cloudhub.io/api", ramlHandler.getBaseUriReplacement("http://0.0.0.0:8081/api")); - - setProperty(FULL_DOMAIN, "pepe.cloudhub.io"); - assertEquals("http://localhost:8081/api/", ramlHandler.getBaseUriReplacement("http://localhost:8081/api/")); - assertEquals("http://pepe.cloudhub.io/api/", ramlHandler.getBaseUriReplacement("http://0.0.0.0:8081/api/")); - - setProperty(FULL_DOMAIN, "http://pepe.cloudhub.io"); - assertEquals("http://pepe.cloudhub.io/api/", ramlHandler.getBaseUriReplacement("http://0.0.0.0:8081/api/")); - - setProperty(FULL_DOMAIN, "http://pepe.cloudhub.io/"); - assertEquals("http://pepe.cloudhub.io/api/", ramlHandler.getBaseUriReplacement("http://0.0.0.0:8081/api/")); - - setProperty(FULL_DOMAIN, "pepe.cloudhub.io/"); - assertEquals("http://pepe.cloudhub.io/api/", ramlHandler.getBaseUriReplacement("http://0.0.0.0:8081/api/")); - - setProperty(FULL_DOMAIN, "pepe.cloudhub.io"); - assertEquals("http://localhost:8081/", ramlHandler.getBaseUriReplacement("http://localhost:8081/")); - assertEquals("http://pepe.cloudhub.io/", ramlHandler.getBaseUriReplacement("http://0.0.0.0:8081/")); - - setProperty(FULL_DOMAIN, "http://pepe.cloudhub.io"); - assertEquals("http://pepe.cloudhub.io/", ramlHandler.getBaseUriReplacement("http://0.0.0.0:8081/")); - - setProperty(FULL_DOMAIN, "http://pepe.cloudhub.io/"); - assertEquals("http://pepe.cloudhub.io/", ramlHandler.getBaseUriReplacement("http://0.0.0.0:8081/")); - - setProperty(FULL_DOMAIN, "pepe.cloudhub.io/"); - assertEquals("http://pepe.cloudhub.io/", ramlHandler.getBaseUriReplacement("http://0.0.0.0:8081/")); - - setProperty(FULL_DOMAIN, "pepe.cloudhub.io"); - assertEquals("http://localhost:8081", ramlHandler.getBaseUriReplacement("http://localhost:8081")); - assertEquals("http://pepe.cloudhub.io", ramlHandler.getBaseUriReplacement("http://0.0.0.0:8081")); - - setProperty(FULL_DOMAIN, "http://pepe.cloudhub.io"); - assertEquals("http://pepe.cloudhub.io", ramlHandler.getBaseUriReplacement("http://0.0.0.0:8081")); - - setProperty(FULL_DOMAIN, "http://pepe.cloudhub.io/"); - assertEquals("http://pepe.cloudhub.io/", ramlHandler.getBaseUriReplacement("http://0.0.0.0:8081")); - - setProperty(FULL_DOMAIN, "pepe.cloudhub.io/"); - assertEquals("http://pepe.cloudhub.io/", ramlHandler.getBaseUriReplacement("http://0.0.0.0:8081")); - - setProperty(FULL_DOMAIN, "pepe.cloudhub.io/api"); - assertEquals("http://pepe.cloudhub.io/api", ramlHandler.getBaseUriReplacement("http://0.0.0.0:8081")); - - setProperty(FULL_DOMAIN, "http://pepe.cloudhub.io/api"); - assertEquals("http://pepe.cloudhub.io/api", ramlHandler.getBaseUriReplacement("http://0.0.0.0:8081")); - - setProperty(FULL_DOMAIN, "http://pepe.cloudhub.io/api"); - assertEquals("http://pepe.cloudhub.io/api", ramlHandler.getBaseUriReplacement("http://0.0.0.0:8081")); - - setProperty(FULL_DOMAIN, "pepe.cloudhub.io/api"); - assertEquals("http://pepe.cloudhub.io/api", ramlHandler.getBaseUriReplacement("http://0.0.0.0:8081")); - } - - @Test - public void consoleUriReplacementTest() { - assertEquals("http://localhost:8081/console", getBaseUriReplacement("http://localhost:8081/console")); - assertEquals("http://localhost:8081/console/", getBaseUriReplacement("http://localhost:8081/console/")); - - setProperty(FULL_DOMAIN, "http://aamura.cloudhub.io/api"); - assertEquals("http://aamura.cloudhub.io/api/console", getBaseUriReplacement("http://0.0.0.0:8081/console")); - assertEquals("http://aamura.cloudhub.io/api/console/", getBaseUriReplacement("http://0.0.0.0:8081/console/")); - - setProperty(FULL_DOMAIN, "http://aamura.cloudhub.io/api/"); - assertEquals("http://aamura.cloudhub.io/api/console", getBaseUriReplacement("http://0.0.0.0:8081/console")); - assertEquals("http://aamura.cloudhub.io/api/console/", getBaseUriReplacement("http://0.0.0.0:8081/console/")); - - setProperty(FULL_DOMAIN, "https://aamura.cloudhub.io/api"); - assertEquals("https://aamura.cloudhub.io/api/console", getBaseUriReplacement("http://0.0.0.0:8081/console")); - assertEquals("https://aamura.cloudhub.io/api/console/", getBaseUriReplacement("http://0.0.0.0:8081/console/")); - - setProperty(FULL_DOMAIN, "https://aamura.cloudhub.io/api/"); - assertEquals("https://aamura.cloudhub.io/api/console", getBaseUriReplacement("http://0.0.0.0:8081/console")); - assertEquals("https://aamura.cloudhub.io/api/console/", getBaseUriReplacement("http://0.0.0.0:8081/console/")); - - setProperty(FULL_DOMAIN, "https://aamura.cloudhub.io/api/v1"); - assertEquals("https://aamura.cloudhub.io/api/v1/console", getBaseUriReplacement("http://0.0.0.0:8081/console")); - assertEquals("https://aamura.cloudhub.io/api/v1/console/", getBaseUriReplacement("http://0.0.0.0:8081/console/")); - - setProperty(FULL_DOMAIN, "aamura.cloudhub.io/api/v1"); - assertEquals("https://aamura.cloudhub.io/api/v1/console", getBaseUriReplacement("https://0.0.0.0:8081/console")); - assertEquals("https://aamura.cloudhub.io/api/v1/console/", getBaseUriReplacement("https://0.0.0.0:8081/console/")); - - assertEquals("http://aamura.cloudhub.io/api/v1/console", getBaseUriReplacement("http://0.0.0.0:8081/console")); - assertEquals("http://aamura.cloudhub.io/api/v1/console/", getBaseUriReplacement("http://0.0.0.0:8081/console/")); - } - - @Test - public void withoutSystemProperty() { - assertEquals("http://localhost:48518/api/", getBaseUriReplacement("http://0.0.0.0:48518/api/")); - assertEquals("http://localhost:48518/api/", getBaseUriReplacement("http://localhost:48518/api/")); - assertNull(getBaseUriReplacement(null)); - - } - - @Test - public void replaceHostWithIncomingRequestHost() { - assertEquals("http://localhost:48518/api", replaceHostInURL("http://0.0.0.0:48518/api", "http://localhost:48518")); - assertEquals("http://localhost:48518/api/", replaceHostInURL("http://0.0.0.0:48518/api/", "http://localhost:48518")); - assertEquals("http://localhost:48518/api/", replaceHostInURL("http://0.0.0.0:48518/api/", "localhost:48518")); - assertEquals("https://127.0.0.1:48518/api/", replaceHostInURL("https://0.0.0.0:48518/api/", "https://127.0.0.1:48518")); - assertEquals("http://192.168.0.196:48518/api/", replaceHostInURL("http://0.0.0.0:48518/api/", "http://192.168.0.196:48518")); - assertEquals("https://192.168.0.196:48518/api/", - replaceHostInURL("https://0.0.0.0:48518/api/", "https://192.168.0.196:48518")); - assertEquals("https://192.168.0.196:48518/api/", replaceHostInURL("https://0.0.0.0:48518/api/", "192.168.0.196:48518")); - } - - @Test - public void replaceHostWithSystemProperty() { - // using host from system property, instead from incoming request - setProperty(FULL_DOMAIN, "aamura.cloudhub.io/v1"); - assertEquals("https://aamura.cloudhub.io/v1/api/", replaceHostInURL("https://0.0.0.0:48518/api/", "192.168.0.196:48518")); - setProperty(FULL_DOMAIN, "https://aamura.cloudhub.io/v1"); - assertEquals("https://aamura.cloudhub.io/v1/api/", replaceHostInURL("https://0.0.0.0:48518/api/", "192.168.0.196:48518")); - } - - @After - public void after() { - clearProperty(FULL_DOMAIN); - } - -} diff --git a/src/test/java/org/mule/module/apikit/deserializing/AttributeDeserializerTest.java b/src/test/java/org/mule/module/apikit/deserializing/AttributeDeserializerTest.java deleted file mode 100644 index f18a06d68..000000000 --- a/src/test/java/org/mule/module/apikit/deserializing/AttributeDeserializerTest.java +++ /dev/null @@ -1,644 +0,0 @@ -/* - * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com - * The software in this package is published under the terms of the CPAL v1.0 - * license, a copy of which has been included with this distribution in the - * LICENSE.txt file. - */ -package org.mule.module.apikit.deserializing; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.mule.module.apikit.api.deserializing.ArrayHeaderDelimiter; - -import java.util.ArrayList; -import java.util.List; - -import static java.util.Arrays.asList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mule.module.apikit.MockingUtils.createEnumValue; -import static org.mule.module.apikit.api.deserializing.ArrayHeaderDelimiter.COMMA; -import static org.mule.module.apikit.deserializing.DeserializerTestBuilder.when; - -@RunWith(Parameterized.class) -public class AttributeDeserializerTest { - - protected static final String TWO_LEVEL_OBJECT = - "{\"color\": \"RED\", \"manufacturer\": {\"brand\": \"Ferrari\"}, \"reseller\": {\"name\": \"YourCar\"}}"; - protected static final String ESCAPED_TWO_LEVEL_OBJECT = - "{\\\"color\\\": \\\"RED\\\", \\\"manufacturer\\\": {\\\"brand\\\": \\\"Ferrari\\\"}, \\\"reseller\\\": {\\\"name\\\": \\\"YourCar\\\"}}"; - - protected static final String TWO_LEVEL_OBJECT_WITH_LINE_FEEDS = "{\n" + - " \"color\": \"RED\",\n" + - " \"manufacturer\": {\n" + - " \"brand\": \"Ferrari\"\n" + - " }\n" + - " \"reseller\": {\n" + - " \"name\": \"YourCar\"\n" + - " }\n" + - "}"; - - protected static final String TWO_LEVEL_OBJECT_BETWEEN_QUOTES = "\"" + ESCAPED_TWO_LEVEL_OBJECT + "\""; - - @Parameterized.Parameter - public ArrayHeaderDelimiter arrayHeaderDelimiter; - @Parameterized.Parameter(1) - public AttributeDeserializer deserializer; - - @Parameterized.Parameters(name = "Delimiter = {0} - {1}") - public static Iterable data() throws Exception { - ArrayHeaderDelimiter comma = COMMA; - ArrayHeaderDelimiter semicolon = createEnumValue(ArrayHeaderDelimiter.class, "SEMICOLON", 2, ";"); - return asList(new Object[][] { - {comma, new ArrayHeaderAttributeDeserializer(comma)}, - {comma, new DummyAttributeDeserializer()}, - {semicolon, new ArrayHeaderAttributeDeserializer(semicolon)} - }); - } - - protected List listOfArrayHeaderValues; - protected String delimiter; - - @Before - public void init() { - delimiter = arrayHeaderDelimiter.getDelimiterValue(); - listOfArrayHeaderValues = new ArrayList<>(); - } - - @Test - public void deserializeEmptyArrayHeader() { - List result = deserializer.deserializeListOfValues(listOfArrayHeaderValues); - assertNotNull(result); - assertEquals(0, result.size()); - } - - @Test - public void blankValuesAsEmptyStringInArrayHeaders() { - String value = " "; - String expected = ""; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(expected) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(expected); - - value = delimiter; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues("", ""); - - value = delimiter + delimiter; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues("", "", ""); - - value = delimiter + " "; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues("", ""); - - value = "\"\"" + delimiter + "\" \""; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues("", " "); - - } - - @Test - public void testSingleValueBetweenEnclosingQuotes() { - String expected = "This is a unique value"; - String value = "\"" + expected + "\""; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(expected) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(expected); - } - - @Test - public void testValueWithDelimitersBetweenEnclosingQuotes() { - String expected = "This " + delimiter + " is a unique" + delimiter + " value"; - String value = "\"" + expected + "\""; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(expected) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(expected); - } - - @Test - public void allowEscapedDoubleQuotesInsideDoubleQuotesInArrayHeaders() { - String value = "\"This is a \\\"string\\\" with \\\"quotes\\\" inside it\""; - String expected = "This is a \"string\" with \"quotes\" inside it"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(expected) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(expected); - - value = "\"commas, between, quotes\\\"" + delimiter + "\\\"semicolon; between; quotes\""; - expected = "commas, between, quotes\"" + delimiter + "\"semicolon; between; quotes"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(expected) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(expected); - } - - @Test - public void deserializeObjectBetweenQuotes() { - String value = TWO_LEVEL_OBJECT_BETWEEN_QUOTES; - String expected = TWO_LEVEL_OBJECT; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(expected) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(expected); - } - - @Test - public void deserializeUnquotedObject() { - String value = TWO_LEVEL_OBJECT; - String expected = value; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(expected) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(expected); - } - - @Test - public void lineFeedOutsideQuotesIsIgnored() { - String value = "\"This is one result\"" + "\n" + delimiter - + "\"This is in a different line and should not be in result\""; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues("This is one result", "This is in a different line and should not be in result"); - } - - @Test - public void lineFeedBetweenQuotesIsIncludedInResult() { - String value = "\"This is one result\n with two lines\"" + delimiter + "\"This is\n another one\""; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues("This is one result\n with two lines", "This is\n another one"); - } - - @Test - public void lineFeedOutsideCurlyBracesIsIgnored() { - String value = "{\"key\": \"value1\"}" + "\n" + delimiter + "{\"key\": \"value2\"}"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues("{\"key\": \"value1\"}", "{\"key\": \"value2\"}"); - } - - @Test - public void lineFeedBetweenCurlyBracesIsIncludedInResult() { - String value = TWO_LEVEL_OBJECT_WITH_LINE_FEEDS + delimiter + TWO_LEVEL_OBJECT_WITH_LINE_FEEDS; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(TWO_LEVEL_OBJECT_WITH_LINE_FEEDS, TWO_LEVEL_OBJECT_WITH_LINE_FEEDS); - } - - @Test - public void carriageReturnOutsideQuotesIsIgnored() { - String value = "\"This is one result\"" + "\r" + delimiter + "\"This is another one\""; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues("This is one result", "This is another one"); - } - - @Test - public void carriageReturnBetweenQuotesIsIncludedInResult() { - String value = "\"This is one result\r with carriage\r returns\"" + delimiter + "\"This is\r another one\""; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues("This is one result\r with carriage\r returns", "This is\r another one"); - } - - @Test - public void carriageReturnBetweenCurlyBracesIsIncludedInResult() { - String value = "{\"key\":\r \"value1\"}" + delimiter + "{\"key\":\r \"value2\"}"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues("{\"key\":\r \"value1\"}", "{\"key\":\r \"value2\"}"); - } - - @Test - public void deserializeValidObjectArrayHeaders() { - String value = "{\"type\": \"username\", \"value\": \"testvalue\"}" - + delimiter - + "{\"type\": \"password\", \"value\": \"testvalue; second\"}"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues("{\"type\": \"username\", \"value\": \"testvalue\"}", - "{\"type\": \"password\", \"value\": \"testvalue; second\"}"); - - - value = "{\"type\": \"fullname\", \"value\": \"Jhon Doe\"}"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues("{\"type\": \"fullname\", \"value\": \"Jhon Doe\"}"); - - - value = TWO_LEVEL_OBJECT + delimiter + TWO_LEVEL_OBJECT; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(TWO_LEVEL_OBJECT, TWO_LEVEL_OBJECT); - - value = TWO_LEVEL_OBJECT_WITH_LINE_FEEDS + delimiter + TWO_LEVEL_OBJECT_WITH_LINE_FEEDS; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(TWO_LEVEL_OBJECT_WITH_LINE_FEEDS, TWO_LEVEL_OBJECT_WITH_LINE_FEEDS); - - value = "\"" + ESCAPED_TWO_LEVEL_OBJECT + delimiter + ESCAPED_TWO_LEVEL_OBJECT + "\""; - String expected = TWO_LEVEL_OBJECT + delimiter + TWO_LEVEL_OBJECT; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(expected) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(expected); - - value = TWO_LEVEL_OBJECT_BETWEEN_QUOTES + delimiter + TWO_LEVEL_OBJECT_BETWEEN_QUOTES; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(TWO_LEVEL_OBJECT, TWO_LEVEL_OBJECT); - } - - @Test - public void deserializeValidArrayHeaders() { - String value = "123" + delimiter + "456" + delimiter + "789"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues("123", "456", "789"); - - value = "1.213" + delimiter + "456" + delimiter + "\"7,123.213\""; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues("1.213", "456", "7,123.213"); - - value = "first" + delimiter + "second" + delimiter + "third"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues("first", "second", "third"); - - value = "\"commas, between, quotes\"" + delimiter + "\"semicolon; between; quotes\""; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues("commas, between, quotes", "semicolon; between; quotes"); - - value = "1985-04-12T23:20:50.52Z" + delimiter - + "\"1996-12-19T16:39:57-08:00\"" + delimiter - + "1937-01-01T12:00:27.87+00:20"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues("1985-04-12T23:20:50.52Z", "1996-12-19T16:39:57-08:00", "1937-01-01T12:00:27.87+00:20"); - - value = "\"" - + "texto" + delimiter - + "t\\\"ext\\\"o" + delimiter - + "t{ext}o" + delimiter - + "{}texto" + delimiter - + "texto{}" + delimiter - + "\\\"texto\\\"{}" + delimiter - + "{}\\\"texto\\\"" - + "\""; - String expected = "texto" + delimiter - + "t\"ext\"o" + delimiter - + "t{ext}o" + delimiter - + "{}texto" + delimiter - + "texto{}" + delimiter - + "\"texto\"{}" + delimiter - + "{}\"texto\""; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(expected) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(expected); - - value = "[{\"test\": 1},{\"test\": \"I have \\\"quotes\\\" inside\"}]"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(value); - } - - @Test - public void deserializeMalformedObjectArrayHeaders() { - String value = "{"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(value); - - value = "["; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(value); - - value = "[{}}"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(value); - - value = "{[]]"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(value); - - value = "{\"username\"}" + delimiter + "{\"testvalue: first\"}" + delimiter + "{testvalue: second}"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues("{\"username\"}", "{\"testvalue: first\"}", "{testvalue: second}"); - - value = "{\"type\": \"username\"{" + delimiter + "\"testvalue: second\"}"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(value); - - value = "{\"type\": \"username\"}}" + delimiter + "{} } "; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues("{\"type\": \"username\"}}", "{} }"); - - value = "{\"type\": }\"username\"" + delimiter + "\"testvalue: second\"}"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues("{\"type\": }\"username\"", "\"testvalue: second\"}"); - - value = "{{{{ }}"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(value); - - value = "{{ }}}}"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(value); - - value = "{{{{ " + delimiter + "}}"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(value); - - value = "asd\"{{{\"asd}}}"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(value); - - value = "asd\\\"{{{\\\"asd}}}"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(value); - - value = "\"\\{\\{\""; - String expected = "\\{\\{"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(expected) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(expected); - - value = "texto" + delimiter - + "t\"ext\"o" + delimiter - + "t{ext}o" + delimiter - + "{}texto" + delimiter - + "texto{}" + delimiter - + "\"texto\"{}" + delimiter - + "{}\"texto\"" + delimiter - + "\"te\\\"x\\\"to\"{}" + delimiter - + "{}\"te\\\"x\\\"to\""; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues("texto", - "t\"ext\"o", - "t{ext}o", - "{}texto", - "texto{}", - "\"texto\"{}", - "{}\"texto\"", - "\"te\\\"x\\\"to\"{}", - "{}\"te\\\"x\\\"to\""); - - value = "[{\"test\": 1},{\"test\": 2}"; - when() - .deserializer(deserializer) - .headerValue(value) - .then() - .on(DummyAttributeDeserializer.class) - .assertValues(value) - .on(ArrayHeaderAttributeDeserializer.class) - .assertValues(value); - } - -} diff --git a/src/test/java/org/mule/module/apikit/validation/body/form/MultipartFormDataTextParameterTestCase.java b/src/test/java/org/mule/module/apikit/validation/body/form/MultipartFormDataTextParameterTestCase.java deleted file mode 100644 index f306fd267..000000000 --- a/src/test/java/org/mule/module/apikit/validation/body/form/MultipartFormDataTextParameterTestCase.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com - * The software in this package is published under the terms of the CPAL v1.0 - * license, a copy of which has been included with this distribution in the - * LICENSE.txt file. - */ -package org.mule.module.apikit.validation.body.form; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyCollection; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.mule.apikit.model.parameter.Parameter; -import org.mule.module.apikit.api.exception.InvalidFormParameterException; -import org.mule.module.apikit.validation.body.form.transformation.MultipartFormDataTextParameter; - -public class MultipartFormDataTextParameterTestCase { - - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - - @Test - public void validateInvalidParameter() throws InvalidFormParameterException { - expectedEx.expect(InvalidFormParameterException.class); - expectedEx.expectMessage("invalid value"); - - Parameter parameter = mock(Parameter.class); - - when(parameter.validate(any())).thenReturn(false); - - when(parameter.message(any())).thenReturn("invalid value"); - - MultipartFormDataTextParameter textParameter = new MultipartFormDataTextParameter("invalid body"); - - textParameter.validate(parameter); - } - - @Test - public void validateValidParameter() throws InvalidFormParameterException { - - Parameter parameter = mock(Parameter.class); - - when(parameter.validate(any())).thenReturn(true); - - MultipartFormDataTextParameter textParameter = new MultipartFormDataTextParameter("valid body"); - - textParameter.validate(parameter); - - } - - @Test - public void validateValidArrayParameter() throws InvalidFormParameterException { - MultipartFormDataTextParameter formDataTextParameter = new MultipartFormDataTextParameter("[123,123]"); - - Parameter parameter = mock(Parameter.class); - when(parameter.isArray()).thenReturn(true); - when(parameter.validateArray(anyCollection())).thenReturn(true); - - formDataTextParameter.validate(parameter); - } - -} diff --git a/src/test/java/org/mule/module/apikit/validation/body/form/MultipartFormValidatorTest.java b/src/test/java/org/mule/module/apikit/validation/body/form/MultipartFormValidatorTest.java deleted file mode 100644 index 24f3fcf26..000000000 --- a/src/test/java/org/mule/module/apikit/validation/body/form/MultipartFormValidatorTest.java +++ /dev/null @@ -1,277 +0,0 @@ -/* - * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com - * The software in this package is published under the terms of the CPAL v1.0 - * license, a copy of which has been included with this distribution in the - * LICENSE.txt file. - */ -package org.mule.module.apikit.validation.body.form; - -import org.apache.commons.io.IOUtils; -import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.mule.apikit.model.parameter.Parameter; -import org.mule.module.apikit.StreamUtils; -import org.mule.module.apikit.api.exception.InvalidFormParameterException; -import org.mule.module.apikit.input.stream.RewindableInputStream; -import org.mule.runtime.api.metadata.DataType; -import org.mule.runtime.api.metadata.MediaType; -import org.mule.runtime.api.metadata.TypedValue; -import org.mule.runtime.api.streaming.CursorProvider; -import org.mule.runtime.api.streaming.bytes.CursorStream; -import org.mule.runtime.api.streaming.bytes.CursorStreamProvider; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.OptionalLong; - -import static java.util.Collections.emptyList; -import static java.util.Collections.emptyMap; -import static java.util.Collections.singletonList; -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class MultipartFormValidatorTest { - - private static final String MULTIPART_SIZE_LIMIT_PROP_NAME = "apikit.multipart.size.limit"; - - public static final String BOUNDARY = "test"; - - public static final String PREAMBLE = "This is the preamble. It is to be ignored, though it \r\n" + - " is a handy place for mail composers to include an \r\n" + - " explanatory note to non-MIME compliant readers.\r\n"; - - public static final String MULTIPART_BODY = - "--test\r\n" + - "Content-Transfer-encoding: 8bit\r\n" + - "Content-type: text/plain; charset=ISO-8859-1\r\n" + - "Content-Disposition: form-data; name=\"file\" filename=\"fileName\"\r\n" + - "\r\n" + - "hello world\r\n" + - "--test\r\n" + - "content-Disposition: form-data; name=\"part1\"\r\n" + - "Custom-Header: customValue; customAttribute=customAttrValue\r\n" + - "Content-Transfer-Encoding: 8bit\r\n" + - "content-Type: text/plain; charset=ISO-8859-1\r\n" + - "\r\n" + - "hello world\r\n" + - "--test--\r\n"; - - public static final String MULTIPART_BODY_WITH_DEFAULT = - "--test\r\n" + - "Content-Transfer-encoding: 8bit\r\n" + - "Content-type: text/plain; charset=ISO-8859-1\r\n" + - "Content-Disposition: form-data; name=\"file\" filename=\"fileName\"\r\n" + - "\r\n" + - "hello world\r\n" + - "--test\r\n" + - "content-Disposition: form-data; name=\"part1\"\r\n" + - "Custom-Header: customValue; customAttribute=customAttrValue\r\n" + - "Content-Transfer-Encoding: 8bit\r\n" + - "content-Type: text/plain; charset=ISO-8859-1\r\n" + - "\r\n" + - "hello world\r\n" + - "--test\r\n" + - "Content-Disposition: form-data; name=\"part2\"\r\n" + - "Content-Type: text/plain; charset=ISO-8859-1\r\n" + - "Content-Transfer-Encoding: 8bit\r\n" + - "\r\n" + - "test\r\n" + - "--test--\r\n"; - - private static final String EPILOGUE = "This is the epilogue. It is also to be ignored.\r\n"; - - private static final String FULL_MULTIPART = PREAMBLE + MULTIPART_BODY + EPILOGUE; - - private static final String FULL_MULTIPART_WITH_DEFAULTS = PREAMBLE + MULTIPART_BODY_WITH_DEFAULT + EPILOGUE; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @After - public void after() { - System.clearProperty(MULTIPART_SIZE_LIMIT_PROP_NAME); - } - - @Test - public void validateCursor() throws Exception { - validateTypedValue(getTypedValue(FULL_MULTIPART), emptyMap(), FULL_MULTIPART); - validateTypedValue(getTypedValue(MULTIPART_BODY), emptyMap(), MULTIPART_BODY); - } - - @Test - public void validateInputStream() throws Exception { - validateTypedValue(getTypedValue(new RewindableInputStream(new ByteArrayInputStream(FULL_MULTIPART.getBytes()))), - emptyMap(), FULL_MULTIPART); - validateTypedValue(getTypedValue(new RewindableInputStream(new ByteArrayInputStream(MULTIPART_BODY.getBytes()))), - emptyMap(), MULTIPART_BODY); - } - - @Test - public void validateDefaultParameters() throws Exception { - Map> formParameters = mockFormParameters(true, "test"); - validateTypedValue(getTypedValue(getCursorStreamProvider(FULL_MULTIPART)), formParameters, FULL_MULTIPART_WITH_DEFAULTS); - validateTypedValue(getTypedValue(getCursorStreamProvider(MULTIPART_BODY)), formParameters, MULTIPART_BODY_WITH_DEFAULT); - validateTypedValue(getTypedValue(new RewindableInputStream(new ByteArrayInputStream(FULL_MULTIPART.getBytes()))), - formParameters, FULL_MULTIPART_WITH_DEFAULTS); - validateTypedValue(getTypedValue(new RewindableInputStream(new ByteArrayInputStream(MULTIPART_BODY.getBytes()))), - formParameters, MULTIPART_BODY_WITH_DEFAULT); - } - - @Test - public void validateRequiredParameters() throws Exception { - Map> formParameters = mockFormParameters(false, null); - validateTypedValue(getTypedValue(new RewindableInputStream(new ByteArrayInputStream(FULL_MULTIPART.getBytes()))), - formParameters, FULL_MULTIPART); - validateTypedValue(getTypedValue(new RewindableInputStream(new ByteArrayInputStream(MULTIPART_BODY.getBytes()))), - formParameters, MULTIPART_BODY); - } - - @Test - public void validateMissingRequiredParameters() throws Exception { - expectedException.expect(InvalidFormParameterException.class); - expectedException.expectMessage(Matchers.equalTo("Required form parameter part2 not specified")); - Map> formParameters = mockFormParameters(true, null); - validateTypedValue(getTypedValue(new RewindableInputStream(new ByteArrayInputStream(FULL_MULTIPART.getBytes()))), - formParameters, FULL_MULTIPART); - validateTypedValue(getTypedValue(new RewindableInputStream(new ByteArrayInputStream(MULTIPART_BODY.getBytes()))), - formParameters, MULTIPART_BODY); - } - - @Test - public void validateMissingRequiredParametersWithDefault() throws Exception { - Map> formParameters = mockFormParameters(true, "test"); - validateTypedValue(getTypedValue(new RewindableInputStream(new ByteArrayInputStream(FULL_MULTIPART.getBytes()))), - formParameters, FULL_MULTIPART_WITH_DEFAULTS); - validateTypedValue(getTypedValue(new RewindableInputStream(new ByteArrayInputStream(MULTIPART_BODY.getBytes()))), - formParameters, MULTIPART_BODY_WITH_DEFAULT); - } - - @Test - public void sizeLimitExceededTest() throws Exception { - expectedException.expect(InvalidFormParameterException.class); - expectedException.expectMessage(Matchers.equalTo("Multipart content exceeded the maximum size supported")); - System.setProperty(MULTIPART_SIZE_LIMIT_PROP_NAME, "250"); - validateTypedValue(getTypedValue(getCursorStreamProvider(FULL_MULTIPART)), emptyMap(), FULL_MULTIPART); - } - - public void validateTypedValue(TypedValue typedValue, Map> formParameters, String expectedPayload) - throws Exception { - MultipartFormValidator multipartFormValidator = new MultipartFormValidator(formParameters); - TypedValue validatedTypedValue = multipartFormValidator.validate(typedValue); - long length = validatedTypedValue.getByteLength().orElse(0); - InputStream validatedInputStream = StreamUtils.unwrapCursorStream(TypedValue.unwrap(validatedTypedValue)); - assertEquals(expectedPayload, IOUtils.toString(validatedInputStream)); - assertEquals(expectedPayload.getBytes().length, length); - } - - private TypedValue getTypedValue(Object value) { - DataType dataType = getDataType(); - return new TypedValue(value, dataType); - } - - private TypedValue getTypedValue(String value) { - DataType dataType = getDataType(); - return new TypedValue(getCursorStreamProvider(value), dataType, getOptionalLong(value)); - } - - private static DataType getDataType() { - return DataType.builder(DataType.INPUT_STREAM) - .mediaType(MediaType.parse("multipart/form-data; boundary=\"" + BOUNDARY + "\"")).build(); - } - - private static OptionalLong getOptionalLong(String value) { - return OptionalLong.of(Integer.valueOf(value.length()).longValue()); - } - - private CursorStreamProvider getCursorStreamProvider(String multipartContent) { - return new CursorStreamProvider() { - - @Override - public CursorStream openCursor() { - return new CursorStream() { - - private final InputStream content = new ByteArrayInputStream(multipartContent.getBytes()); - - @Override - public int read() throws IOException { - return content.read(); - } - - @Override - public long getPosition() { - return 0; - } - - @Override - public void seek(long position) { - - } - - @Override - public void release() { - - } - - @Override - public boolean isReleased() { - return false; - } - - @Override - public CursorProvider getProvider() { - return null; - } - }; - } - - @Override - public void close() { - - } - - @Override - public void releaseResources() { - - } - - @Override - public boolean isClosed() { - return false; - } - }; - } - - private Map> mockFormParameters(boolean allRequired, String defaultValue) { - - Parameter part1 = mock(Parameter.class); - Parameter part2 = mock(Parameter.class); - - when(part1.getFileProperties()).thenReturn(Optional.empty()); - when(part2.getFileProperties()).thenReturn(Optional.empty()); - - when(part1.isRequired()).thenReturn(true); - when(part2.isRequired()).thenReturn(allRequired); - - when(part2.getDefaultValues()).thenReturn(defaultValue != null ? singletonList(defaultValue) : emptyList()); - - when(part1.validate(anyString())).thenReturn(true); - when(part2.validate(anyString())).thenReturn(true); - - Map> formParameters = new HashMap<>(); - formParameters.put("part1", singletonList(part1)); - formParameters.put("part2", singletonList(part2)); - - return formParameters; - } - -} diff --git a/src/test/java/org/mule/module/apikit/validation/body/form/MultipartWithDefaultsBinaryParameterTestCase.java b/src/test/java/org/mule/module/apikit/validation/body/form/MultipartWithDefaultsBinaryParameterTestCase.java deleted file mode 100644 index 935c39086..000000000 --- a/src/test/java/org/mule/module/apikit/validation/body/form/MultipartWithDefaultsBinaryParameterTestCase.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com - * The software in this package is published under the terms of the CPAL v1.0 - * license, a copy of which has been included with this distribution in the - * LICENSE.txt file. - */ -package org.mule.module.apikit.validation.body.form; - -import static java.util.Optional.of; -import static org.junit.Assert.assertThrows; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.mule.runtime.api.metadata.MediaType.parse; - -import com.google.common.collect.ImmutableSet; -import java.util.Optional; - -import org.junit.Test; -import org.mule.apikit.model.parameter.FileProperties; -import org.mule.apikit.model.parameter.Parameter; -import org.mule.module.apikit.api.exception.InvalidFormParameterException; -import org.mule.module.apikit.validation.body.form.transformation.MultipartFormDataBinaryParameter; - -public class MultipartWithDefaultsBinaryParameterTestCase { - - @Test(expected = InvalidFormParameterException.class) - public void invalidContentType() throws Exception { - Parameter parameter = getParameter(0, 0, "image/png"); - validate(parameter, "image/jpeg"); - } - - @Test - public void parameterWithoutFileProperties() throws Exception { - Parameter parameter = mock(Parameter.class); - when(parameter.getFileProperties()).thenReturn(Optional.empty()); - validate(parameter, "image/jpeg"); - } - - @Test - public void validContentTypeAndNoSizeRestriction() throws Exception { - Parameter parameter = getParameter(0, 0, "image/png", "image/jpeg"); - validate(parameter, "image/jpeg"); - } - - @Test(expected = InvalidFormParameterException.class) - public void sizeLowerThanMinLength() throws Exception { - Parameter parameter = getParameter(16, 20, "image/png", "image/jpeg"); - validate(parameter, "image/jpeg"); - } - - @Test(expected = InvalidFormParameterException.class) - public void sizeBiggerThanMaxLength() throws Exception { - Parameter parameter = getParameter(10, 14, "image/png", "image/jpeg"); - validate(parameter, "image/jpeg"); - } - - @Test - public void validSize() throws Exception { - Parameter parameter = getParameter(15, 15, "image/png", "image/jpeg"); - validate(parameter, "image/jpeg"); - } - - @Test - public void anyFileTypeAllowed() throws Exception { - Parameter parameter = getParameter(0, 0, "*/*"); - validate(parameter, "image/jpeg"); - } - - @Test - public void emptyFileTypes() throws Exception { - Parameter parameter = getParameter(0, 0); - validate(parameter, "image/jpeg"); - } - - @Test - public void subtypeWildcard() throws Exception { - Parameter parameter = getParameter(0, 0, "image/*"); - validate(parameter, "image/jpeg"); - } - - @Test - public void extraParametersAreIgnored() throws Exception { - Parameter parameter = getParameter(0, 0, "text/plain"); - validate(parameter, "text/plain; charset=utf8"); - } - - @Test - public void parameterQuotingIsIgnored() throws Exception { - Parameter parameter = getParameter(0, 0, "text/plain; my-param=\"my-value\"; another-param=another-value"); - validate(parameter, "text/plain; my-param=my-value; another-param=\"another-value\""); - } - - @Test - public void parameterOrderIsNotImportant() throws Exception { - Parameter parameter = getParameter(0, 0, "text/plain; a=b; b=c"); - validate(parameter, "text/plain; b=c; a=b"); - } - - @Test - public void parametersAreValidatedAsRequired() throws Exception { - Parameter parameter = getParameter(0, 0, "text/plain; myParam=test"); - // Parameter missing - assertThrows(InvalidFormParameterException.class, () -> validate(parameter, "text/plain")); - // Parameter has wrong value - assertThrows(InvalidFormParameterException.class, () -> validate(parameter, "text/plain; myparam=toast")); - // Parameter is ok - validate(parameter, "text/plain; myparam=\"test\""); - } - - @Test - public void charsetParametersAreValidatedRespectingAliases() throws Exception { - Parameter parameter = getParameter(0, 0, "text/plain; charset=utf8"); - // Parameter missing - assertThrows(InvalidFormParameterException.class, () -> validate(parameter, "text/plain")); - // Parameter has wrong value - assertThrows(InvalidFormParameterException.class, () -> validate(parameter, "text/plain; charset=ascii")); - // Parameter is ok - validate(parameter, "text/plain; CharSet=\"utf8\""); - validate(parameter, "text/plain; CharSet=\"utf-8\""); - validate(parameter, "text/plain; CharSet=\"UTF-8\""); - } - - @Test - public void wildcardTypesValidateParameters() throws Exception { - Parameter parameter = getParameter(0, 0, "*/*; loves-mule=yes"); - - validate(parameter, "text/plain; loves-mule=yes"); - validate(parameter, "image/png; loves-mule=yes; extra-param=ignored"); - assertThrows(InvalidFormParameterException.class, () -> validate(parameter, "text/plain; loves-mule=no")); - assertThrows(InvalidFormParameterException.class, () -> validate(parameter, "image/png")); - } - - @Test - public void wildcardSubtypesValidateParameters() throws Exception { - Parameter parameter = getParameter(0, 0, "image/*; loves-mule=yes"); - - validate(parameter, "image/webp; loves-mule=yes"); - validate(parameter, "image/png; loves-mule=yes; extra-param=ignored"); - assertThrows(InvalidFormParameterException.class, () -> validate(parameter, "image/webp; loves-mule=no")); - assertThrows(InvalidFormParameterException.class, () -> validate(parameter, "image/png")); - assertThrows(InvalidFormParameterException.class, () -> validate(parameter, "text/plain; loves-mule=yes")); - } - - @Test(expected = InvalidFormParameterException.class) - public void illegalCharsetsFailValidation() throws Exception { - Parameter parameter = getParameter(0, 0, "text/plain; charset=invalid-charset!"); - validate(parameter, "text/plain; charset=ascii"); - } - - @Test(expected = InvalidFormParameterException.class) - public void illegalMimeFailValidation() throws Exception { - Parameter parameter = getParameter(0, 0, "this is not a valid mime!"); - validate(parameter, "text/plain; charset=ascii"); - } - - private Parameter getParameter(int minLength, int maxLength, String... mediaTypes) { - Parameter parameter = mock(Parameter.class); - FileProperties properties = new FileProperties(minLength, maxLength, ImmutableSet.copyOf(mediaTypes)); - when(parameter.getFileProperties()).thenReturn(of(properties)); - return parameter; - } - - private void validate(Parameter parameter, String mediaType) throws InvalidFormParameterException { - MultipartFormDataBinaryParameter parameterValidator = - new MultipartFormDataBinaryParameter("testing payload".getBytes().length, parse(mediaType)); - parameterValidator.validate(parameter); - } -} diff --git a/src/test/java/org/mule/module/apikit/validation/body/schema/RestJsonSchemaValidatorTestCase.java b/src/test/java/org/mule/module/apikit/validation/body/schema/RestJsonSchemaValidatorTestCase.java deleted file mode 100644 index 6658f1e95..000000000 --- a/src/test/java/org/mule/module/apikit/validation/body/schema/RestJsonSchemaValidatorTestCase.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com - * The software in this package is published under the terms of the CPAL v1.0 - * license, a copy of which has been included with this distribution in the - * LICENSE.txt file. - */ -package org.mule.module.apikit.validation.body.schema; - -import static org.mockito.Mockito.when; -import org.mule.module.apikit.Configuration; -import org.mule.module.apikit.api.RamlHandler; -import org.mule.module.apikit.api.exception.BadRequestException; -import org.mule.module.apikit.validation.body.schema.v1.RestJsonSchemaValidator; -import org.mule.apikit.model.Action; -import org.mule.apikit.model.ActionType; -import org.mule.apikit.model.MimeType; -import org.mule.apikit.model.ApiSpecification; -import org.mule.apikit.model.Resource; -import org.mule.runtime.api.exception.TypedException; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import javax.xml.validation.Schema; - -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.mockito.Mockito; - -public class RestJsonSchemaValidatorTestCase { - - private static final String jsonSchema = "{\n" + - " \"$schema\" : \"http://json-schema.org/draft-03/schema\",\n" + - " \"title\": \"League Schema\",\n" + - " \"type\": \"object\",\n" + - " \"properties\": {\n" + - " \"id\": {\n" + - " \"type\": \"string\"\n" + - " },\n" + - " \"name\": {\n" + - " \"type\": \"string\",\n" + - " \"required\": true\n" + - " }\n" + - " }\n" + - "}\n"; - private static ApiSpecification api; - private static Action mockedAction; - - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @BeforeClass - public static void mockApi() { - api = Mockito.mock(ApiSpecification.class); - - MimeType mimeType = Mockito.mock(MimeType.class); - Map compiledSchemaMap = new HashMap<>(); - Map body = new HashMap<>(); - Schema compiledSchema = org.raml.parser.visitor.SchemaCompiler.getInstance().compile(jsonSchema); - - compiledSchemaMap.put("scheme-json", compiledSchema); - when(api.getCompiledSchemas()).thenReturn(compiledSchemaMap); - - Map schemaMap = new HashMap<>(); - schemaMap.put("scheme-json", jsonSchema); - when(api.getConsolidatedSchemas()).thenReturn(schemaMap); - - when(mimeType.getType()).thenReturn("application/json"); - when(mimeType.getSchema()).thenReturn("scheme-json"); - body.put("application/json", mimeType); - - mockedAction = Mockito.mock(Action.class); - when(mockedAction.getBody()).thenReturn(body); - - Resource mockedResource = Mockito.mock(Resource.class); - - when(mockedResource.getAction("POST")).thenReturn(mockedAction); - when(mockedResource.getResolvedUri(api.getVersion())).thenReturn("/leagues"); - - when(mockedAction.getResource()).thenReturn(mockedResource); - when(mockedAction.getType()).thenReturn(ActionType.POST); - - when(api.getResource("/leagues")).thenReturn(mockedResource); - } - - @Test - public void validStringPayloadUsingParser() throws TypedException, ExecutionException, BadRequestException { - - String payload = "{ \"name\": \"Major League Soccer\" }"; - RamlHandler ramlHandler = Mockito.mock(RamlHandler.class); - - Configuration config = new Configuration(); - when(ramlHandler.getApi()).thenReturn(api); - config.setRamlHandler(ramlHandler); - - RestJsonSchemaValidator JsonSchemavalidator = - new RestJsonSchemaValidator(config.getJsonSchema("/leagues,POST,application/json").getSchema()); - - JsonSchemavalidator.validate(payload); - } - - @Test(expected = BadRequestException.class) - public void invalidStringPayloadUsingParser() throws TypedException, BadRequestException, ExecutionException { - String payload = "{ \"naazame\": \"Major League Soccer\" }"; - Configuration config = new Configuration(); - RamlHandler ramlHandler = Mockito.mock(RamlHandler.class); - - when(ramlHandler.getApi()).thenReturn(api); - config.setRamlHandler(ramlHandler); - - RestJsonSchemaValidator jsonSchemavalidator = - new RestJsonSchemaValidator(config.getJsonSchema("/leagues,POST,application/json").getSchema()); - jsonSchemavalidator.validate(payload); - } - - @Test - public void showAllSchemaValidationErrors() throws TypedException, BadRequestException, ExecutionException { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(VALIDATION_ERRORS_EXPECTED_MESSAGE); - - String payload = "{ \"id\": 1 }"; - Configuration config = new Configuration(); - RamlHandler ramlHandler = Mockito.mock(RamlHandler.class); - - when(ramlHandler.getApi()).thenReturn(api); - config.setRamlHandler(ramlHandler); - - RestJsonSchemaValidator jsonSchemavalidator = - new RestJsonSchemaValidator(config.getJsonSchema("/leagues,POST,application/json").getSchema()); - jsonSchemavalidator.validate(payload); - } - - private static final String VALIDATION_ERRORS_EXPECTED_MESSAGE = - "error: object has missing required properties ([\"name\"])\n" + - " level: \"error\"\n" + - " schema: {\"loadingURI\":\"#\",\"pointer\":\"\"}\n" + - " instance: {\"pointer\":\"\"}\n" + - " domain: \"validation\"\n" + - " keyword: \"properties\"\n" + - " required: [\"name\"]\n" + - " missing: [\"name\"]\n" + - "\n" + - "error: instance type (integer) does not match any allowed primitive type (allowed: [\"string\"])\n" + - " level: \"error\"\n" + - " schema: {\"loadingURI\":\"#\",\"pointer\":\"/properties/id\"}\n" + - " instance: {\"pointer\":\"/id\"}\n" + - " domain: \"validation\"\n" + - " keyword: \"type\"\n" + - " found: \"integer\"\n" + - " expected: [\"string\"]\n" + - "\n"; -} diff --git a/src/test/java/org/mule/module/apikit/validation/body/schema/RestSchemaV2ValidatorTestCase.java b/src/test/java/org/mule/module/apikit/validation/body/schema/RestSchemaV2ValidatorTestCase.java deleted file mode 100644 index 8c4ced4f0..000000000 --- a/src/test/java/org/mule/module/apikit/validation/body/schema/RestSchemaV2ValidatorTestCase.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com - * The software in this package is published under the terms of the CPAL v1.0 - * license, a copy of which has been included with this distribution in the - * LICENSE.txt file. - */ -package org.mule.module.apikit.validation.body.schema; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.mule.apikit.model.MimeType; -import org.mule.apikit.validation.ApiValidationResult; -import org.mule.module.apikit.api.exception.BadRequestException; -import org.mule.module.apikit.validation.body.schema.v2.RestSchemaV2Validator; - -import static java.util.Arrays.asList; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class RestSchemaV2ValidatorTestCase { - - @Rule - public ExpectedException expected = ExpectedException.none(); - - @Test - public void buildLogMessage() throws Exception { - expected.expect(BadRequestException.class); - expected.expectMessage("Message 0\nMessage 1"); - - MimeType mimeTypeMock = mock(MimeType.class); - RestSchemaV2Validator validator = new RestSchemaV2Validator(mimeTypeMock); - - ApiValidationResult validationResult0 = mock(ApiValidationResult.class); - when(validationResult0.getMessage()).thenReturn("Message 0"); - ApiValidationResult validationResult1 = mock(ApiValidationResult.class); - when(validationResult1.getMessage()).thenReturn("Message 1"); - - when(mimeTypeMock.validate(any(String.class))).thenReturn( - asList(validationResult0, validationResult1)); - - validator.validate("{\"test\" : \"test\"}"); - } - -} diff --git a/src/test/java/org/mule/module/apikit/validation/body/schema/RestXMLSchemaValidatorTestCase.java b/src/test/java/org/mule/module/apikit/validation/body/schema/RestXMLSchemaValidatorTestCase.java deleted file mode 100644 index 84aaacd31..000000000 --- a/src/test/java/org/mule/module/apikit/validation/body/schema/RestXMLSchemaValidatorTestCase.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com - * The software in this package is published under the terms of the CPAL v1.0 - * license, a copy of which has been included with this distribution in the - * LICENSE.txt file. - */ -package org.mule.module.apikit.validation.body.schema; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ExecutionException; - -import javax.xml.validation.Schema; - -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.mockito.Mockito; - -import org.mule.module.apikit.Configuration; -import org.mule.module.apikit.api.RamlHandler; -import org.mule.module.apikit.api.exception.BadRequestException; -import org.mule.module.apikit.validation.body.schema.v1.RestXmlSchemaValidator; -import org.mule.apikit.model.Action; -import org.mule.apikit.model.MimeType; -import org.mule.apikit.model.ApiSpecification; -import org.mule.apikit.model.Resource; -import org.mule.runtime.api.exception.ErrorTypeRepository; -import org.mule.runtime.api.exception.TypedException; -import org.mule.runtime.api.message.ErrorType; - -public class RestXMLSchemaValidatorTestCase { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - private static final String xmlSchema = "" + - "" + - "" + - " " + - " " + - " " + - " " + - " " + - " " + - "" + - ""; - - private static ApiSpecification api; - - @BeforeClass - public static void mockApi() { - api = Mockito.mock(ApiSpecification.class); - - Map compiledSchemaMap = new HashMap<>(); - Schema compiledSchema = org.raml.parser.visitor.SchemaCompiler.getInstance().compile(xmlSchema); - compiledSchemaMap.put("scheme-xml", compiledSchema); - when(api.getCompiledSchemas()).thenReturn(compiledSchemaMap); - - Map schemaMap = new HashMap<>(); - schemaMap.put("scheme-xml", xmlSchema); - when(api.getConsolidatedSchemas()).thenReturn(schemaMap); - - Map body = new HashMap<>(); - MimeType mimeType = Mockito.mock(MimeType.class); - when(mimeType.getType()).thenReturn("application/xml"); - when(mimeType.getSchema()).thenReturn("scheme-xml"); - body.put("application/xml", mimeType); - Action mockedAction = Mockito.mock(Action.class); - when(mockedAction.getBody()).thenReturn(body); - Resource mockedResource = Mockito.mock(Resource.class); - when(mockedResource.getAction("POST")).thenReturn(mockedAction); - when(api.getResource("/leagues")).thenReturn(mockedResource); - } - - @Test - public void validStringPayloadUsingParser() throws TypedException, ExecutionException, BadRequestException { - String payload = "MLS"; - String schemaPath = "/leagues,POST,application/xml"; - - Configuration config = new Configuration(); - RamlHandler ramlHandler = Mockito.mock(RamlHandler.class); - ErrorTypeRepository errorTypeRepository = Mockito.mock(ErrorTypeRepository.class); - when(ramlHandler.getApi()).thenReturn(api); - config.setRamlHandler(ramlHandler); - - RestXmlSchemaValidator xmlValidator = new RestXmlSchemaValidator(config.getXmlSchema(schemaPath), errorTypeRepository); - - xmlValidator.validate(payload); - } - - @Test(expected = TypedException.class) - public void invalidStringPayloadUsingParser() throws TypedException, BadRequestException, ExecutionException { - String payload = "hello"; - String schemaPath = "/leagues,POST,application/xml"; - - Configuration config = new Configuration(); - RamlHandler ramlHandler = Mockito.mock(RamlHandler.class); - when(ramlHandler.getApi()).thenReturn(api); - config.setRamlHandler(ramlHandler); - - RestXmlSchemaValidator xmlValidator = new RestXmlSchemaValidator(config.getXmlSchema(schemaPath)); - xmlValidator.validate(payload); - } - - @Test - public void xxeAttackIsDisabled() throws TypedException, ExecutionException, BadRequestException { - - expectedException.expectMessage("An internal operation failed."); - - String payload = "\n" - + "" - + "]>\n" - + "&mls;"; - - String schemaPath = "/leagues,POST,application/xml"; - - Configuration config = new Configuration(); - RamlHandler ramlHandler = Mockito.mock(RamlHandler.class); - ErrorTypeRepository errorTypeRepository = Mockito.mock(ErrorTypeRepository.class); - ErrorType type = mock(ErrorType.class); - when(errorTypeRepository.getErrorType(any())).thenReturn(Optional.of(type)); - when(ramlHandler.getApi()).thenReturn(api); - config.setRamlHandler(ramlHandler); - - RestXmlSchemaValidator xmlValidator = new RestXmlSchemaValidator(config.getXmlSchema(schemaPath), errorTypeRepository); - - xmlValidator.validate(payload); - } -} diff --git a/src/test/munit/error/api-errors-test-suite.xml b/src/test/munit/error/api-errors-test-suite.xml index a6c64588a..4c99f2957 100644 --- a/src/test/munit/error/api-errors-test-suite.xml +++ b/src/test/munit/error/api-errors-test-suite.xml @@ -78,7 +78,7 @@ - +